首页 > 解决方案 > 如何计算图像边界框中包含的像素簇的加权(灰度)质心

问题描述

我在 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


%% 


标签: matlabimage-processinggrayscalecentroid

解决方案


推荐阅读