MATLAB写二值图的最小外接圆和最大内接圆程序
时间: 2024-05-09 19:14:42 浏览: 168
以下是MATLAB代码,实现二值图的最小外接圆和最大内接圆:
```matlab
% 读入二值图像
bw = imread('binary_image.png');
% 计算最小外接圆
s = regionprops(bw, 'BoundingBox');
center = [s.BoundingBox(1) + s.BoundingBox(3)/2, s.BoundingBox(2) + s.BoundingBox(4)/2];
d = sqrt(sum((s.BoundingBox(3:4)).^2));
radius = d/2;
figure, imshow(bw), hold on
viscircles(center, radius, 'Color', 'r');
% 计算最大内接圆
dist = bwdist(~bw);
max_radius = max(dist(:));
center = find(dist == max_radius);
[x, y] = ind2sub(size(bw), center(1));
figure, imshow(bw), hold on
viscircles([y, x], max_radius, 'Color', 'g');
```
解释一下代码:
1. 读入二值图像。
2. 使用`regionprops`函数计算二值图像的外接矩形。然后根据外接矩形的大小计算最小外接圆的圆心和半径。
3. 使用`viscircles`函数在图像上绘制最小外接圆。
4. 使用`bwdist`函数计算二值图像中每个像素到最近背景像素的距离,即距离变换。因为最大内接圆的直径一定是背景像素之间的距离,所以最大内接圆的半径就是距离变换中的最大值。
5. 找到距离变换中最大值的位置,即最大内接圆的圆心。
6. 使用`viscircles`函数在图像上绘制最大内接圆。
注意,这段代码仅适用于二值图像。如果是灰度图像或彩色图像,需要将其转换为二值图像。
阅读全文
相关推荐















