点击下方卡片,关注“ OpenCV与AI深度学习”
视觉/图像重磅干货,第一时间送达!
导读本文主要介绍一个在低对比度图像中提取圆形轮廓的实例,并将Halcon实现转为OpenCV。实例来源
Halcon例程dyn_threshold.hdev--动态阈值算子使用实例。原图:
Halcon实现效果:
OpenCV实现步骤与代码
实现步骤:【1】dyn_threshold操作替代--均值滤波+图像差分+阈值提取
【2】圆形结构元素闭运算+开运算【3】轮廓查找+最小外接圆【4】标注结果:圆心+外圆轮廓
逐步效果演示与代码:完整源码:
#--公众号:OenCV与AI深度学习#--Author:Color Spaceimport numpy as np
import cv2
font=cv2.FONT_HERSHEY_SIMPLEX
img = cv2.imread('embossed_01.png')
cv2.imshow('src', img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.blur(gray, (50,50))
cv2.imshow('blur', blur)
diff = cv2.absdiff(gray, blur)
cv2.imshow('diff', diff)
ret,thres = cv2.threshold(diff,15,255,cv2.cv2.THRESH_BINARY)
cv2.imshow('thres', thres)
k1 = np.zeros((19, 19),np.uint8)cv2.circle(k1,(9,9),9,(1,1,1),-1,cv2.LINE_AA)
closing = cv2.morphologyEx(thres, cv2.MORPH_CLOSE, k1, None, None, 1)#闭运算cv2.imshow('closing',closing)
k2 = np.zeros((13, 13),np.uint8)cv2.circle(k2,(6,6),6,(1,1,1),-1,cv2.LINE_AA)
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, k2, None, None, 1)#闭运算cv2.imshow('opening',opening)
contours,hierarchy = cv2.findContours(opening, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)count = 0for cnt in contours: center,radius = cv2.minEnclosingCircle(cnt) if radius < 5: continue count = count + 1 cv2.circle(img,(int(center[0]),int(center[1])),int(radius),(0,255,0),2) cv2.drawMarker(img,(int(center[0]),int(center[1])),(0,0,255), cv2.MARKER_CROSS, 15,1,8)strCount = "count = %d" % countcv2.putText(img,strCount,(10,30),font,1.0,(255,0,0),2)
cv2.imshow('result', img)cv2.imwrite('result.jpg', img)
cv2.waitKey(0)cv2.destroyAllWindows()原图:
均值滤波结果图:
差分图像:
阈值结果:
闭运算结果:
开运算结果:
最终结果:
—THE END—
下载1:Pytorch常用函数手册
在「OpenCV与AI深度学习」公众号后台回复:Pytorch函数手册,即可下载学习全网第一份Pytorch函数常用手册,包括Tensors介绍、基础函数介绍、数据处理函数、优化函数、CUDA编程、多处理等十四章内容。
下载2:145个OpenCV实例应用代码
在「OpenCV与AI深度学习」公众号后台回复:OpenCV145,即可下载学习145个OpenCV实例应用代码(Python和C++双语言实现)。
欢迎加入CV学习交流微信群!
觉得有用,记得点个赞和在看
|