clc;
clear;
close all;
% 读取图像
pic = imread('test.jpg'); % Make sure this points to the correct file path
gray_pic = rgb2gray(pic);
% 使用灰度图进行二值化
binary_img = 1 - imbinarize(gray_pic, 0.73);
% 填充区域和删除小对象
fill_hole = imfill(binary_img, 'holes');
small_objects_removed = bwareaopen(fill_hole, 80);
% 对比填充后和原始的二值图像,找出空洞和缺陷
defects_img = fill_hole - binary_img;
% 提取边界和计算区域属性
[B, L] = bwboundaries(small_objects_removed, 'noholes');
out_result = regionprops(small_objects_removed, 'Extent', 'Centroid', 'BoundingBox', 'Perimeter', 'Area');
% 显示原始图像
figure;
imshow(pic);
title('圆形、三角形、正方形和长方形检测');
hold on;
% 形状识别和显示
for i = 1:length(out_result)
centroid = out_result(i).Centroid;
bbox = out_result(i).BoundingBox;
circularity = 4 * pi * out_result(i).Area / (out_result(i).Perimeter^2);
% 检测是否有空洞或缺陷
defect_area = bwarea(defects_img(L == i));
if circularity > 0.8
if defect_area > 0 % 如果有空洞或缺陷
shape = '有缺陷的圆';
end
else
shape = '圆形';
end
if out_result(i).Extent > 0.54
% 计算长宽比,来区分正方形和长方形
aspect_ratio = bbox(3) / bbox(4);
if abs(aspect_ratio - 1) < 0.1 % 长宽比接近1则认为是正方形
shape = '正方形';
else
shape = '长方形';
end
else
shape = '三角形';
end
text(centroid(1)-40, centroid(2), shape, 'Color', 'w', 'FontSize', 12, 'FontWeight', 'bold');
end
% 绘制边界
for j = 1:length(B)
boundary = B{j};
plot(boundary(:, 2), boundary(:, 1), 'r', 'LineWidth', 2);
end
hold off;