导 读
本文主要介绍Halcon转OpenCV实例--纺织物折痕检测(附源码)。
实例来源
实例来源于《Halcon机器视觉算法原理与编程实战》7.4.2实例
下面测试图片也来源于图书代码,如有侵权请联系删除:
上图肉眼可见的折痕,类似脏污,我们的目的是将折痕检测出来。
Halcon实现
测试图:
实现代码与效果(书中代码用到了texture_laws纹理检测,实际测试发现,直接处理S通道即可得到比较好的效果,所以代码中去除了纹理检测方法):
read_image(Image,'cloth.jpg')*将图像分解成RGB三个通道decompose3(Image, R, G, B)*将RGB三个通道的图像,转化为HSV图像空间trans_from_rgb(R, G, B, H, S, V, 'hsv')*二值化分割threshold(S, Regions, 37, 255)*开运算剔除噪点opening_circle(Regions, RegionOpening, 4.5)fill_up(RegionOpening, RegionFillUp)connection(RegionFillUp, ConnectedRegions)select_shape(ConnectedRegions, SelectedRegions, 'area', 'and', 5000, 100000)count_obj(SelectedRegions, Number)dev_get_window(WindowHandle)fori := 1 to Number by 1dev_display(Image)*dev_set_draw('margin')*dev_set_line_width(2)select_obj(SelectedRegions, ObjectSelected, i)disp_region(ObjectSelected,WindowHandle)endfor
实现效果:
OpenCV实现步骤与代码
测试图:
实现步骤:
【1】转到HSV颜色空间,分离HSV通道,下面分别是H、S、V通道的效果图
img = cv2.imread("cloth.jpg")hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)h,s,v = cv2.split(hsv_img)
【2】S通道二值化,开运算
ret,thres_img = cv2.threshold(s,35,255,cv2.THRESH_BINARY)k1=np.ones((9,9), np.uint8)opening = cv2.morphologyEx(thres_img, cv2.MORPH_OPEN, k1)
【3】查找轮廓,轮廓筛选,绘制结果
contours,hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for i in range(len(contours)): (x, y, w, h) = cv2.boundingRect(contours) print(w,h) if w > 50 and h > 50: cv2.drawContours(img,contours,i,(0,0,255),-1)
完整代码:#公众号:OpenCV与AI深度学习#作 者:Color Spaceimport numpy as npimport cv2
img = cv2.imread("cloth.jpg")hsv_img = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv_img)cv2.imshow('H',h)cv2.imshow('S',s) cv2.imshow('V',v)
ret,thres_img = cv2.threshold(s,35,255,cv2.THRESH_BINARY)cv2.imshow("thres_img", thres_img)cv2.imwrite('thres_img.jpg',thres_img)
k1=np.ones((9,9), np.uint8)opening = cv2.morphologyEx(thres_img, cv2.MORPH_OPEN, k1)
cv2.imshow('open', opening)cv2.imwrite('open.jpg',opening)
contours,hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)for i in range(len(contours)): (x, y, w, h) = cv2.boundingRect(contours) print(w,h)if w > 50and h > 50: cv2.drawContours(img,contours,i,(0,0,255),-1)
cv2.imshow('result',img)cv2.imwrite('res.jpg',img)
cv2.waitKey(0)cv2.destroyAllWindows()
相关文章推荐:
Halcon缺陷检测实例转OpenCV实现(一)
Halcon缺陷检测实例转OpenCV实现(二)
Halcon缺陷检测实例转OpenCV实现(三)
Halcon缺陷检测实例转OpenCV实现(四)
Halcon缺陷检测实例转OpenCV实现(五) 混合颜色药片缺陷检测
Halcon缺陷检测实例转OpenCV实现(六) 瓶口缺陷检测
Halcon转OpenCV实例--复杂背景下缺陷检测(附源码)
Halcon转OpenCV实例--去除纸张中的颜色笔迹/墨迹(附源码)
Halcon实例转OpenCV--低对比度图像中提取圆形轮廓(附源码)
实战 | Halcon实例转OpenCV实现-复杂背景下OCR数字识别(附源码)
|