Halcon转OpenCV实例--复杂背景下缺陷检测(附源码)

2021-07-01 09:34:02 浏览数 (1)

导读

本文主要介绍一个复杂背景下缺陷检测的实例,并将Halcon实现转为OpenCV。

实例来源

实例来源于51Halcon论坛的讨论贴:

https://www.51halcon.com/forum.php?mod=viewthread&tid=1173&extra=page=1

Halcon实现

参考回帖内容,将代码精简如下:

代码语言:javascript复制
read_image (Image, './1.bmp')
dev_set_line_width (3)
threshold (Image, Region, 30, 255)
reduce_domain (Image, Region, ImageReduced)
mean_image (ImageReduced, ImageMean, 200, 200)
dyn_threshold (ImageReduced, ImageMean, SmallRaw, 35, 'dark')
opening_circle (SmallRaw, RegionOpening, 8)
closing_circle (RegionOpening, RegionClosing, 10)
connection (RegionClosing, ConnectedRegions)
dev_set_color ('red')
dev_display (Image)
dev_set_draw ('margin')
dev_display (ConnectedRegions)

如上图所示,可以较好的定位缺陷位置。

OpenCV实现

分析实现方法与思路:

[1] 原图转灰度图后使用核大小201做中值滤波;

[2] 灰度图与滤波图像做差,然后阈值处理

[3] 圆形核做开运算,去除杂讯

[4] 圆形核做闭运算,缺陷连接

[5] 轮廓查找绘制

实现代码(Python-OpenCV):

代码语言:javascript复制
import cv2
import numpy as np

img = cv2.imread('./1.bmp')
cv2.imshow('src',img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

mean = cv2.medianBlur(gray,201)
cv2.imshow('mean',mean)

#diff = cv2.absdiff(gray, mean)
diff = gray - mean
cv2.imshow('diff',diff)
cv2.imwrite('diff.jpg',diff)
_,thres_low = cv2.threshold(diff,150,255,cv2.THRESH_BINARY)#二值化
_,thres_high = cv2.threshold(diff,220,255,cv2.THRESH_BINARY)#二值化
thres = thres_low - thres_high
cv2.imshow('thres',thres)

k1 = np.zeros((18,18,1), np.uint8)
cv2.circle(k1,(8,8),9,(1,1,1),-1, cv2.LINE_AA)
k2 = np.zeros((20,20,1), np.uint8)
cv2.circle(k2,(10,10),10,(1,1,1),-1, cv2.LINE_AA)
opening = cv2.morphologyEx(thres, cv2.MORPH_OPEN, k1)
cv2.imshow('opening',opening)
closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, k2)
cv2.imshow('closing',closing)

contours,hierarchy = cv2.findContours(closing, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for cnt in contours:
  (x, y, w, h) = cv2.boundingRect(cnt)
  if w > 5 and h > 5:
      #cv2.rectangle(img,(x,y),(x w,y h),(0,255,0),2)
      cv2.drawContours(img,contours,-1,(0,0,255),2)

cv2.drawContours(img,cnt,2,(0,0,255),2)
cv2.imshow('result',img)

cv2.waitKey(0)
cv2.destroyAllWindows()
print('Done!')

逐步效果演示

滤波效果:mean

做差效果:diff

阈值效果:thres

开运算效果:opening

闭运算效果:closing

轮廓查找绘制最终结果:

结尾语

[1] 算法只是针对这一张图片,实际应用为验证算法鲁棒性还需大量图片做测试方可;

[2] 缺陷检测如果用传统方法不易实现,可以考虑使用深度学习分割网络如:mask-rcnn、U-net等

完整代码与素材将发布在知识星球中,有兴趣可加入获取。

0 人点赞