【发布时间】:2019-09-28 04:32:03
【问题描述】:
我在 MATLAB 中编写了一些代码,它使用设定的阈值将图像(星形)转换为二进制图像,然后标记高于此阈值的每个像素簇(星形)。标签产生输出: 例如
[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]
所以每个由 1、2、3 等组成的星团代表一颗星。我使用此链接提供的答案:How to find all connected components in a binary image in Matlab? 来标记像素。在此之后,代码会找到每个像素簇的面积和质心。
我现在想包含一些代码,这些代码将自动绘制以每个质心为中心的某个像素区域的框。例如,质心的位置为 [41, 290],像素簇的面积为 6 像素,我想绘制一个面积为 nx 6 像素的框,框的中心为 [41, 290] .我需要这个循环遍历每个质心并做同样的事情。
我该怎么做呢?
质心和区号如下所示。
%% 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
【问题讨论】:
-
'ID_counter' undefined near line 24 column 12。应该只是N? -
啊,是的,我之前在代码中指定了 ID_counter,但 N 也应该可以工作。
-
你应该编辑你的代码/问题。如果提供的代码不能开箱即用,人们可能会不愿意帮助您。
-
我现在已经添加了完整的代码。应该一切正常。
-
好的,谢谢,我已将“ID_counter”更改为“N”。
标签: matlab image-processing centroid