复杂背景下缺陷检测将Halcon实现转为OpenCV的实例

描述

导读 本文主要介绍一个复杂背景下缺陷检测的实例,并将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深度学习

编辑:jq

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分