I have array of floating points Nx2 which is representing the reprojected 3D -> 2D coordinates in a 2D image. I need to find closest (integer) pixel. The naive solution is pretty simple:
import numpy as np
# Original array of floating-point row and column values
points = np.array([
[327.47910325, 3928.36321963],
[1439.79734793, 3987.02652005],
[304.02698845, 2844.82490694],
[230.43053757, 4090.70452501]
])
def find_nearest_integer_point(point):
# Extract the row and column values
row, col = point
# Four possible nearest integer points
candidates = np.array([
[np.floor(row), np.floor(col)],
[np.floor(row), np.ceil(col)],
[np.ceil(row), np.floor(col)],
[np.ceil(row), np.ceil(col)]
])
# Calculate the Euclidean distances to the candidates
distances = np.linalg.norm(candidates - point, axis=1)
# Select the candidate with the minimum distance
nearest_point = candidates[np.argmin(distances)]
return nearest_point.astype(int)
# Apply the function to each point
rounded_points = np.array([find_nearest_integer_point(point) for point in points])
print(rounded_points)
But this for sure will be extremely inefficient once working with big amounts of data (2D videos instead of a single image).
Anyone could advise me on a some speed-up for the given method? Maybe something already implemented in some publicly available library? Or maybe some data structure I should take into account?