I've written some code in MATLAB that converts an image (of stars) into a binary image using a set threshold and then labels each cluster of pixels (stars) that is above this threshold. The labelling produces an output: e.g.
[1 1 1 0 0 0 0 0 0
1 1 0 0 0 2 2 2 0
0 0 0 3 3 0 2 0 0
0 0 0 3 3 0 0 0 0]
So each cluster of 1's, 2's, 3's etc. represents a star. I used the answer provided at this link: How to find all connected components in a binary image in Matlab? to label the pixels. After this the code then finds the area and centroids of each pixel cluster.
I now want to include some code that will automatically draw boxes of a certain pixel area centered on each centroid. For example, a centroid has a location of [41, 290] and the pixel cluster has an area of 6 pixels, I want to draw a box with an area of n x 6 pixels with the centre of the box being [41, 290]. And I need this to loop through every centroid and do the same.
How would I go about doing this?
The centroid and area code is shown below.
%% Calculate centroids of each labelled pixel cluster within binary image
N = max(B(:)); % total number of pixel labels generated in output array B
sum_v = zeros(N,1); % create N x 1 array of 0's
sum_iv = zeros(N,1); % "
sum_jv = zeros(N,1); % "
for jj=1:size(B,2) % search through y positions
for ii=1:size(B,1) % search through x positions
index = B(ii,jj);
if index>0
sum_v(index) = sum_v(index) + 1;
sum_iv(index) = sum_iv(index) + ii;
sum_jv(index) = sum_jv(index) + jj;
end
end
end
centroids = [sum_jv, sum_iv] ./ sum_v % calculates centroids for each cluster
for pp = 1:N
id_index = find(B == pp);
pixels = numel(id_index); % counts number of pixels in each cluster
area(pp) = pixels; % area = no. of pixels per cluster
end
hold on
for i=1:size(centroids,1)
plot(centroids(i,1),centroids(i,2),'rx','MarkerSize',10)
end
hold off