1

How can I efficiently find all pixels (u',v') within a distance x from a given pixel (u,v). Specifically all (u',v') such that sqrt((u-u')^2 +(v-v')^2) <= x

Adriaan
  • 17,741
  • 7
  • 42
  • 75
delhi_loafer
  • 119
  • 8

2 Answers2

2

To find all pixels at distance x you can use this indexing trick (for Manhattan distance)

u=10;v=10;
x=3.4;
pixels=img([floor(u-x) ceil(u+x)],[floor(v-x) ceil(v+x)]);

However, note that this will add any pixel that is within the distance, even if its just a piece of the pixel! E.g. (6,6) is inside!


For Euclidean distance, you need to define a circle around the point

[xi,yi]=meshgrid(1:size(img,1),1:size(img,2));
mask=sqrt((xi-u).^2+(yi-v).^2)<x; % or ceil(x)
pixel_values=img(mask);
[pixel_indices_u pixel_indices_v]=find(mask);
Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
2
u = rand(1e2,1); % Create a 100 random points in the unit square
v = rand(1e2,1); % Create a 100 random points in the unit square
a = 0.3; % Choosen pixel
b = 0.4;
x = 0.1; % radius from the choosen pixel

idx = (sqrt((u-a).^2 +(v-b).^2) <= x); % Create a logical index array
locs = [u(idx) v(idx)]; % Index the locations

This is basically exactly what you describe in the question, with the points being labelled as (u,v) and the "destination point" so to speak labelled with (a,b) as a prime (') denotes the complex conjugate transpose in MATLAB.

Read more on logical indexing in this very insightful answer by Luis Mendo

Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75