Halcon轉(zhuǎn)OpenCV實例--復雜背景下缺陷檢測(附源碼)
實例來源

Halcon實現(xiàn)
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實現(xiàn)
import cv2import numpy as npimg = 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!')
逐步效果演示




閉運算效果:closing

輪廓查找繪制最終結(jié)果:

結(jié)尾語
—版權(quán)聲明—
來源:OpenCV與AI深度學習
僅用于學術(shù)分享,版權(quán)屬于原作者。
若有侵權(quán),請聯(lián)系微信號:yiyang-sy 刪除或修改!
評論
圖片
表情
