如何在 Matlab 中将不同的形状转换为圆形

How to transform different shapes to circles in Matlab

我有这张图片:

有不同的形状,我想将每个形状变换成一个圆圈。并且每个圆必须有不同的半径,这取决于形状的大小。我怎样才能做到这一点?使用形态学操作或 Matlab 上有任何功能可以做到这一点吗? 我使用了Regionprops函数来检测每一个单独的形状,然后我可以对每个区域分别进行操作。

我会使用 bwlabel 首先标记所有组件。然后我会使用 regionprops 来找到每个组件的边界框。然后,您可以使用具有 Curvature[1 1]rectangle 在每个边界框处绘制一个椭圆。

%// Load the image and convert to 0's and 1's
img = imread('http://i.stack.imgur.com/9wRYK.png');
img = double(img(:,:,1) > 0);

%// Label the image
L = bwlabel(img);

%// Compute region properties
P = regionprops(L);

imshow(img)

for k = 1:numel(P)
    %// Get the bounding box
    bb = P(k).BoundingBox;

    %// Plot an ellipse around each object
    hold on
    rectangle('Position', bb, ...
              'Curvature', [1 1], ...
              'EdgeColor', 'r', ...
              'LineWidth', 2);
end

如果您真的想要圆,则需要确定如何从矩形定义圆。为此,我只使用宽度和高度中的最大值作为直径。

t = linspace(0, 2*pi, 100);
cost = cos(t);
sint = sin(t);

for k = 1:numel(P)
    bb = P(k).BoundingBox;

    %// Compute the radius and center of the circle
    center = [bb(1)+0.5*bb(3), bb(2)+0.5*bb(4)];
    radius = max(bb(3:4)) / 2;

    %// Plot each circle
    plot(center(1) + radius * cost, ...
         center(2) + radius * sint, ...
         'Color', 'r');
end

现在如果你真的想修改图像 data 本身而不是简单地显示它,你可以使用所有像素中心的 meshgrid 来测试是否给定像素是否在圆内。

%// Create a new image the size of the old one
newImage = zeros(size(img));

%// Determine the x/y coordinates for each pixel
[xx,yy] = meshgrid(1:size(newImage, 2), 1:size(newImage, 1));
xy = [xx(:), yy(:)];

for k = 1:numel(P)
    bb = P(k).BoundingBox;

    %// Compute the circle that fits each bounding box
    center = [bb(1)+0.5*bb(3), bb(2)+0.5*bb(4)];
    radius = max(bb(3:4)) / 2;

    %// Now check if each pixel is within this circle
    incircle = sum(bsxfun(@minus, xy, center).^2, 2) <= radius^2;

    %// Change the values of newImage
    newImage(incircle) = k;
end

%// Create a binary mask of all points that were within any circle
mask = newImage > 0;