導讀 本文主要介紹一個復雜背景下缺陷檢測的實例,并將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
-
濾波
+關注
關注
10文章
667瀏覽量
56646 -
OpenCV
+關注
關注
31文章
635瀏覽量
41350 -
HALCON
+關注
關注
16文章
64瀏覽量
27224 -
深度學習
+關注
關注
73文章
5503瀏覽量
121162
原文標題:Halcon轉OpenCV實例--復雜背景下缺陷檢測(附源碼)
文章出處:【微信號:vision263com,微信公眾號:新機器視覺】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
評論