如何计算图像边界框内包含的像素簇的加权(灰度)质心

时间:2019-05-20 13:38:26

标签: matlab image-processing grayscale centroid

我已经在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等的每个簇代表一个星星。此后,代码将找到每个像素簇的质心,并在每个质心周围(以质心为中心)绘制一个具有8 x 8像素面积的边界框。边界框限制是通过找到每个计算出的质心的xmax,xmin,ymax,ymin来确定的,这涉及从每个质心的x和y坐标相加或减去4(像素)。

加权质心的计算如下:

x_coordinate_centroid = sum(x_coordinate。* pixel_values)/ sum_pixel_values y_coordinate_centroid = sum(y_coordinate。* pixel_values)/ sum_pixel_values

x / y_coordinate和像素值用于每个边界框中包含的像素。

边界框将在灰度图像上围绕8 x 8像素区域(具有给定强度),例如:

[100 100 100 90  20  20  0   0
 80  90  100 90  20  30  0   0
 50  70  100 70  30  0   20  0
 50  0   0   60  30  30  0   0
 0   0   0   0   0   0   0   0
 0   50  0   0   0   0   0   0
 0   40  0   0   0   0   0   0
 0   20  0   0   0   0   0   0]

例如,左上角的值([xmin,ymax])可以具有图像坐标[41,14],强度为100。

例如,我代码的输出可以在灰度图像上提供5个边界框。现在,我需要编写代码来自动计算每个边界框区域的加权质心。我不确定该怎么做,有人知道如何实现吗?

我的计算质心及其边界框的代码如下所示。


%% Calculate centroids of each labelled pixel cluster within binary image

N = max(B(:));    % total number of pixel labels generated in output array
sum_total = zeros(N,1);    % create N x 1 array of 0's
sum_yv = zeros(N,1);    % "
sum_xv = zeros(N,1);    % "
for xx=1:size(B,2)    % search through y positions
   for yy=1:size(B,1)    % search through x positions
      index = B(yy,xx);
      if index>0
          sum_total(index) = sum_total(index) + 1;
          sum_yv(index) = sum_yv(index) + yy;
          sum_xv(index) = sum_xv(index) + xx;
      end
   end
end
centroids = [sum_xv, sum_yv] ./ sum_total;    % calculates centroids for each cluster


x_lower_limits = centroids(:,1)-4;
y_lower_limits = centroids(:,2)+4;    % lower on image means larger y coord number
x_upper_limits = centroids(:,1)+4;
y_upper_limits = centroids(:,2)-4;    % higher on image means lower y coord number


x_lower_limits(x_lower_limits<1)=1;    % limit smallest x coord to image axis (1,y)
y_lower_limits(y_lower_limits>size(binary_image,1))=size(binary_image,1);    % limit largest y coord to image axis (x,517)
x_upper_limits(x_upper_limits>size(binary_image,2))=size(binary_image,2);    % limit largest x coord to image axis (508,y)
y_upper_limits(y_upper_limits<1)=1;    % limit smallest y coord to image axis (x,1)


width = x_upper_limits(:,1) - x_lower_limits(:,1);    % width of bounding box
height = y_lower_limits(:,1) - y_upper_limits(:,1);    % height of bounding box


hold on

for xl=1:size(x_lower_limits,1)
               r(xl)=rectangle('Position',[x_lower_limits(xl,1) y_upper_limits(xl,1) width(xl,1) height(xl,1)],'EdgeColor','r');


end
for i=1:size(centroids,1)
    plot(centroids(i,1),centroids(i,2),'rx','MarkerSize',10)
end
hold off


%% 


0 个答案:

没有答案