文档库 最新最全的文档下载
当前位置:文档库 › circledetect圆的检测程序matlab

circledetect圆的检测程序matlab

function circledetect()

%----------Step 1:
clc
RGB = imread('findcircle.png');
subplot(2,2,1);
imshow(RGB);
title('原始图像');


%----------Step 2: 图像阈值
% Convert the image to black and white in order to prepare for boundary tracing using bwboundaries.
I = rgb2gray(RGB); %彩色变换成灰色
threshold = graythresh(I);%graythresh为自动的找出灰度图像的阈值
bw = im2bw(I,threshold); %im2bw应用阈值把灰度图像转化为而至图像
subplot(2,2,2);
imshow(bw);
title('二值化图像');



% ------------Step 3: 去噪
% 应用形态学函数去噪, 去除不感兴趣的像素.
bw = bwareaopen(bw,30); %bwareaopen去除含有小于30的像素的对象
subplot(2,2,3);
imshow(bw);
title('形态学去噪后图像');
se = strel('disk',2);%strel创建一个半径为2像素的结构元素
bw = imclose(bw,se);%imclose对图像进行闭运算,使得图像边界线没有小的不连接缝隙
subplot(2,2,4);
imshow(bw);
title('闭运算后的图像');
bw = imfill(bw,'holes'); %填充封闭区域或者空洞



%------Step 4: 寻找边界
[B,L] = bwboundaries(bw,'noholes'); %bwboundaries寻找二值图像的边界,“noholes”为外边界,返回值B为边界像素所在的坐标,L??????
% returns the label matrix, L, as the second
% output argument. Objects and holes are labeled. L is a two-dimensional
% array of nonnegative integers that represent contiguous regions. The
% k-th region includes all elements in L that have value k. The number of
% objects and holes represented by L is equal to max(L(:))
figure(2)
imshow(label2rgb(L, @jet, [0.5 0.5 0.5])) ; % label2rge把图像标记为@jet彩色,背景默认为灰色
hold on
for k = 1:length(B) % length行列中的最大值
boundary = B{k}; % B{k}每一个图形边界对应的坐标值
plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)%描画每一个图形的边界
end



%------------------Step 5: 决定那个图形为圆形
%估计每个形状的面积跟周长,用这个结果指明对象的圆度。
area1=0;
perimeter=0;
metric = 4*pi*area1/perimeter^2; % perimeter为周长
%这个矩阵在对象是圆的时候值为1,当是其他对象时小于1,通过阈值来控制这个过程,本例中阈值为0.94,所以只有
%薄片能够被分类为圆,对每个对象使用regionprops函数来获得估计面积值,可以看出,标记矩阵L仍然被用于下边程序中,
stats = regionprops(L,'Area','Centroid'); %测量标注矩阵L中每一个标注区的圆、形心属性。返回值stats为结构矩阵,
%返回一个长度为max(L(:))结构数组,结构数组相应域下储存每一个标注区域的属性。
threshold = 0.94;
for k = 1:length(B) %逐个获取对象
boundary = B{k} %每个对象边缘的坐标值
delta_sq = diff(boundary).^2 %某一个边界线上一点的坐标值与临近点坐标值的差分的绝对值,diff为求差分
p

erimeter = sum(sqrt(sum(delta_sq,2))); % sum(,2)列相加的开方,及就是相邻两点之间距离之和,也就是整个边界的近似周长
area1 = stats(k).Area; % 第K个对象的面积
metric = 4*pi*area1/perimeter^2;
metric_string = sprintf('%2.2f',metric);%‘%2.2f’以小数形式输出metric,保留两位小数。
if metric > threshold
centroid = stats(k).Centroid
plot(centroid(1),centroid(2),'ko');%在满足阈值条件的图形中心标记黑圆圈。
end

text(boundary(1,2)-35,boundary(1,1)+13,metric_string,'Color','y',...
'FontSize',14,'FontWeight','bold'); %在每个边界的起始点偏离设定位置黄色显示小数
end

title(['显示数值越接近1,表明图形越接近圆']);



相关文档