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

时间:2016-04-17 22:59:38

标签: matlab image-processing image-morphology

我有这张图片:

enter image description here

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

enter image description here

1 个答案:

答案 0 :(得分:3)

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

%// 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

enter image description here

如果您确实需要圆圈,则需要确定从矩形中精确定义圆圈的方式。为此,我只使用了直径的最大宽度和高度。

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

enter image description here

现在,如果您确实想要修改图像数据本身而不是简单地显示它,您可以使用所有像素中心的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;

enter image description here