# Remove centroid locations of objects that are too close

3 Ansichten (letzte 30 Tage)
Jason am 8 Aug. 2022
Kommentiert: Jason am 9 Aug. 2022
Hi, I have a list of centroid locations of spots in an image (xf, yf). The spots are randomly distributed. I want to remove the centroid locations that are too close to each other, or say within a distance of d. I've got to the following but not sure what to do next. Also is there a better way to do this ratrher than use loops?
%using a loop
M=[];
for j=1:length(xf)
for i=1:length(xf)
dx=xf(j)-xf(i);
dy=yf(j)-yf(i);
dr=sqrt(power(dx,2)+power(dy,2));
M(j,1)=xf(j);
M(j,2)=yf(j);
M(j,3)=xf(i);
M(j,4)=yf(i);
M(j,5)=dr;
end
end
##### 2 KommentareKeine anzeigenKeine ausblenden
Matt J am 9 Aug. 2022
If two spots are less than d apart should both be removed? If not, by what criterion do you decide which spot remains?
Image Analyst am 9 Aug. 2022
To me it sounds like both are to be removed. This is easily done with pdist2.

Melden Sie sich an, um zu kommentieren.

### Akzeptierte Antwort

Matt J am 9 Aug. 2022
Bearbeitet: Matt J am 9 Aug. 2022
A=[xf(:) yf(:)];
D=pdist2(A,A);
D(D==0)=inf; %retroactive EDIT
keep = all(D>d,1);
xf=xf(keep);
yf=yf(keep);
##### 7 Kommentare5 ältere Kommentare anzeigen5 ältere Kommentare ausblenden
Jason am 9 Aug. 2022
Of course, its clear now, thankyou
Jason am 9 Aug. 2022
Just to add, when I had over 400 objects, akthough i do other operations, using the for loop took 110s.using the pdist2 approach took just under 2s. Remarkable!

Melden Sie sich an, um zu kommentieren.

### Weitere Antworten (1)

yanqi liu am 9 Aug. 2022
yes，sir，may be use pdist2， such as
xf = rand(1, 10);
yf = rand(1, 10);
%using a loop
M=[];
for j=1:length(xf)
for i=1:length(xf)
dx=xf(j)-xf(i);
dy=yf(j)-yf(i);
dr=sqrt(power(dx,2)+power(dy,2));
M(end+1,1)=xf(j);
M(end,2)=yf(j);
M(end,3)=xf(i);
M(end,4)=yf(i);
M(end,5)=dr;
end
end
% second method
A=[xf(:) yf(:)];
B=pdist2(A,A);
C=B';
C=C(:);
isequal(M(:,end),C)
ans = logical
1
##### 0 Kommentare-2 ältere Kommentare anzeigen-2 ältere Kommentare ausblenden

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Timing and presenting 2D and 3D stimuli finden Sie in Help Center und File Exchange

R2022a

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by