工业缺陷检测有很多应用的地方,如汽车轮毂制造的缺陷、手机壳的缺陷、太阳能电池板的缺陷等等。由于问题比较简单,这次针对太阳能电池板进行缺陷检测,即电池板上有很多条状撕裂细纹或者小斑点视为缺陷。由于图像很多(成千上万,每块板有6*10小块,基本均匀大小分布),这里只给出代表性的一整块太阳能电池板,其中最后一小块(patch)有细纹缺陷,其他小块略有斑点缺陷。
这里主要用基本的图像处理技术即可识别出缺陷,其主要算法思路为:
这里给出实现代码和识别结果。
%% 用于太阳能电池板缺陷检测,缺陷用红色标记,正常就不标记
patch_rows = 6;
patch_cols = 10;
imds = imageDatastore('./defect_image_cell',... % 改成自己.jpg图像所在目录即可
'includeSubfolders',true,...
'fileExtensions',{'.jpg'});
nums = length(imds.Files);
%% main loop
for k = 1:nums
img1 = imresize(readimage(imds,k),0.3);
if size(img1,3)==3
img1 = rgb2gray(img1);
end
%% get max rect
bw = imbinarize(img1,0.35);
se = strel('disk',3);
bw_close = imclose(bw,se);
s = regionprops(bw_close,'BoundingBox');
max_area = 0;
max_rect = [];
for i = 1:length(s)
area = s(i).BoundingBox(3)*s(i).BoundingBox(4);
if area>=max_area
max_area = area;
max_rect = s(i).BoundingBox;
end
end
%% get all patches rects
x = linspace(max_rect(1),max_rect(1)+max_rect(3),11);
y = linspace(max_rect(2),max_rect(2)+max_rect(4),7);
[X,Y] = meshgrid(x,y);
square_rects = zeros(patch_rows*patch_cols,4);
for i = 1:patch_rows
for j = 1:patch_cols
square_rects(patch_cols*(i-1)+j,:) = [X(i,j),Y(i,j),X(i,j+1)-X(i,j),Y(i+1,j)-Y(i,j)];
current_rect = square_rects(patch_cols*(i-1)+j,:);
end
end
%% detect each patch defect
img1_RGB = cat(3,img1,img1,img1);
for i = 1:patch_rows*patch_cols
x = floor(square_rects(i,1));
y = floor(square_rects(i,2));
width = floor(square_rects(i,3));
height = floor(square_rects(i,4));
current_patch = img1(y:(y+height),x:(x+width));
[bw_ed,threshOut] = edge(current_patch,'prewitt',0.040);
SE = strel('disk',3,6);
dilate_img = imdilate(bw_ed,SE);
[bw,threshold] = edge(current_patch,'canny',[0.0585,0.2563]);
border = round(0.12*size(bw,1));
bw_mask = false(size(bw));
bw_mask(border:size(bw,1)-border,border:size(bw,2)-border) = true;
mask = bw_mask&bw;
mask = mask&(~dilate_img);
R = current_patch;G = current_patch;B = current_patch;
R(mask) = 255;G(mask) = 0;B(mask) = 0;
draw_patch = cat(3,R,G,B);
img1_RGB(y:(y+size(draw_patch,1)-1),x:(x+size(draw_patch,2)-1),:) = draw_patch;
end
[path,name,~] = fileparts(imds.Files{k});
save_name = fullfile(path,[name,'_draw.png']);
imwrite(img1_RGB,save_name);
% imshowpair(img1,img1_RGB,'montage')
end
识别结果图:
所有源码和图像这里下载。