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

新机器视觉

共 3003字,需浏览 7分钟

 ·

2021-07-04 01:23

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

实例来源

实例来源于51Halcon论坛的讨论贴:
https://www.51halcon.com/forum.php?mod=viewthread&tid=1173&extra=page%3D1

Halcon实现

参考回帖内容,将代码精简如下:
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):
import cv2import 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 - meancv2.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_highcv2.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等

—版权声明—

来源:OpenCV与AI深度学习

仅用于学术分享,版权属于原作者。

若有侵权,请联系微信号:yiyang-sy 删除或修改!


—THE END—

浏览 7
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报