function clusters = find_clusters(image, thresholdValue, neighborDistance, minimumClusterSize)
% find_clusters(image, thresholdValue, neighborDistance, minimumClusterSize).Finds clusters in the given 2D image.
%
% Finds clusters in the given 2D image.All pixels in the cluster are >= thresholdValue and <= neighborDistance% pixel-widths away from at least one other pixel in the cluster.Only clusters with at least minimumClusterSize% pixels in them are returned.The return value is a 1xN cell array, where N is the number of clusters found.Each cell% contains a Mx2 array of the locations (row, col) of the M pixels in the cluster.%% Threshold the image and get a list of pixels that exceed the thresholdthresh = image >= thresholdValue;
[rows, cols] = find(thresh == 1);
visited = zeros(size(image));
clusters = {};
% for each white pixel
for p = 1:length(rows)
r = rows(p);
c = cols(p);
if visited(r, c) == 0
visited(r,c) = 1;
cluster = [];
% Use depth-first-search to find neighbors and add them to the cluster
build_cluster(r, c);
if length(cluster) > minimumClusterSize
clusters = [clusters cluster];
end
end
end
% Recursive function to perform DFS on neighbor white pixels.Note
% that this has been set up as a nested function so that we dont have to
% make repeated copies of the cluster, thresh, and visited arrays.
function build_cluster(r, c)
cluster= [cluster; r, c];
visited(r,c) = 1;
ndi = round(neighborDistance / sqrt(2));
neighborRows = max(1, r ndi):min(size(thresh,1), r + ndi);
neighborCols = max(1, c ndi):min(size(thresh,2), c + ndi);
for nr = neighborRows
for nc = neighborCols
if ~(nr == r && nc == c)
dist = sqrt((nr-r)^2 + (nc-c)^2);
if dist <= neighborDistance && thresh(nr, nc) == 1 && visited(nr, nc) == 0build_cluster(nr, nc);endendendendendend
Reviews
There are no reviews yet.