工业检测中铁罐焊缝检测
程序员文章站
2022-03-29 22:47:41
...
工业检测中铁罐焊缝检测
算法用到了边缘检测,均值滤波和霍夫变换
话不多说,直接上代码
clc
clear
%预处理
f=imread('0.jpg');o=f;
f=rgb2gray(f);f=im2double(f);
figure();subplot(2,2,1);imshow(o);title('原图');
[m,n]=size(f);
%canny 边缘检测
I=edge(f,'Canny',0.05);
subplot(2,2,2);imshow(I);title('canny算子提取图像边缘');
%均值滤波
[m,n]=size(I);
for i=2:m-1
for j=2:n-1
y(i,j)=I(i-1,j-1)+I(i-1,j)+I(i-1,j+1)+I(i,j-1)+I(i,j)+I(i,j+1)+I(i+1,j-1)+I(i+1,j)+I(i+1,j+1);
y(i,j)=y(i,j)/9;
%提取边缘后,对结果进行均值滤波以去除噪声,为下一步hough变换提取直线作准备
end
end
subplot(2,2,3);imshow(y);title('均值滤波器处理后');
%二值化
q=im2uint8(y); %把图像数据类型转换为无符号八位整型
[m,n]=size(q);
for i=1:m
for j=1:n
if q(i,j)>80%设置二值化的阈值为80
q(i,j)=255;%对图像进行二值化处理,使图像边缘更加突出清晰
else
q(i,j)=0;
end
end
end
subplot(2,2,4);imshow(q);title('二值化处理后');
%% Find the longest line segment based on Hough transform.
[x, y] = mylineextraction(q);
% Plot the line in the image
figure; imshow(f), title('霍夫变换后的结果')
hold on
plot([x(1) y(1)], [x(2) y(2)],'LineWidth',2,'Color','blue');
plot(x(1),x(2),'x','LineWidth',2,'Color','red');
plot(y(1),y(2),'x','LineWidth',2,'Color','red');
hold off
自定义霍夫直线检测函数
function [bp, ep] = mylineextraction(BW)
% The function extracts the longest line segment from the given binary image
% Input parameter:
% BW = A binary image.
%
% Output parameters:
% [bp, ep] = beginning and end points of the longest line found
% in the image.
[n, m] = size(BW);
[H,T,R] = hough(BW);
P = houghpeaks(H,8,'threshold',ceil(0.2*max(H(:))));
lines= houghlines(BW,T,R,P,'FillGap',20,'MinLength',7);
maxLength = 0;
for k = 1:length(lines)
xy = [lines(k).point1; lines(k).point2];
if (((xy(1,1) - xy(2,1))^2 + (xy(1,2) - xy(2,2))^2) > maxLength)
maxLength = (xy(1,1) - xy(2,1))^2 + (xy(1,2) - xy(2,2))^2;
bp = xy(1,:);
ep = xy(2,:);
end
end
原图
结果图
借鉴了哪些博客我已经找不到了,如有侵权请联系我!