时间:2022-12-29 10:52:09 | 栏目:Python代码 | 点击:次
通常提取物体的轮廓时,图像都存在噪声,提取效果并不理想。如提取下图的轮廓时,
提取代码:
import cv2 img = cv2.imread("mouse.png") cv2.imshow("origin",img) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ret,binary = cv2.threshold(gray,128,255,cv2.THRESH_BINARY) cv2.imshow("binary",binary) contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(img,contours,-1,(0,0,255),3) cv2.imshow("result", img) cv2.waitKey(0)
提取效果:
可以看出存在非常严重的噪声干扰。因此,提取轮廓之前需要过滤噪声的干扰。
首先,进行对图像进行均值滤波(低通滤波),去除噪声
blured = cv2.blur(img,(5,5)) cv2.imshow("blur",blured)
使用floodfill来去掉目标周围的背景,泛洪填充类始于ps的魔棒工具,这里用来清除背景。
mask = np.zeros((h+2, w+2), np.uint8) #掩码长和宽都比输入图像多两个像素点,泛洪填充不会超出掩码的非零边缘 #进行泛洪填充 cv2.floodFill(blured, mask, (10,10), (255,255,255), (2,2,2),(3,3,3),8) cv2.imshow("floodfill", blured)
floodFill函数解析
然后转换成灰度图
gray = cv2.cvtColor(blured,cv2.COLOR_BGR2GRAY) cv2.imshow("gray", gray)
此时目标图像周围有写不光滑,还有一些噪声,因此进行开闭运算,得到比较光滑的目标
#定义结构元素 kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(50, 50)) #开闭运算,先开运算去除背景噪声,再继续闭运算填充目标内的孔洞 opened = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel) closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel) cv2.imshow("closed", closed)
接着转换成二值图以便于获取图像的轮廓
最后进行轮廓提取,抓取到目标
#找到轮廓 _,contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #绘制轮廓 cv2.drawContours(img,contours,-1,(0,0,255),3) #绘制结果 cv2.imshow("result", img)
全部代码:
#coding=utf-8 import cv2 import numpy as np img = cv2.imread("temp.jpg") #载入图像 h, w = img.shape[:2] #获取图像的高和宽 cv2.imshow("Origin", img) #显示原始图像 blured = cv2.blur(img,(5,5)) #进行滤波去掉噪声 cv2.imshow("Blur", blured) #显示低通滤波后的图像 mask = np.zeros((h+2, w+2), np.uint8) #掩码长和宽都比输入图像多两个像素点,满水填充不会超出掩码的非零边缘 #进行泛洪填充 cv2.floodFill(blured, mask, (w-1,h-1), (255,255,255), (2,2,2),(3,3,3),8) cv2.imshow("floodfill", blured) #得到灰度图 gray = cv2.cvtColor(blured,cv2.COLOR_BGR2GRAY) cv2.imshow("gray", gray) #定义结构元素 kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(50, 50)) #开闭运算,先开运算去除背景噪声,再继续闭运算填充目标内的孔洞 opened = cv2.morphologyEx(gray, cv2.MORPH_OPEN, kernel) closed = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel) cv2.imshow("closed", closed) #求二值图 ret, binary = cv2.threshold(closed,250,255,cv2.THRESH_BINARY) cv2.imshow("binary", binary) #找到轮廓 _,contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #绘制轮廓 cv2.drawContours(img,contours,-1,(0,0,255),3) #绘制结果 cv2.imshow("result", img) cv2.waitKey(0) cv2.destroyAllWindows()
总结