© Fu Xianjun. All Rights Reserved. 今天小赵带大家进入openCV的图像轮廓,素材依然来自我们的小傅老师,这次他给我们准备的素材很不错。
图像轮廓
前言
图像轮廓是openCV里面的一个很重要的部分,和很多内容都会有所链接,希望大家和我好好学习。
提示:以下是本篇文章正文内容,下面案例可供参考
一、图像轮廓需要什么?
我们看一下知识点
二、图像轮廓的实现
1.查找轮廓
关键代码知识点
mode:
cv2.RETR_EXTERNAL 只检测外轮廓
cv2.RETR_LIST检测的轮廓不建立等级关系
cv2.RETR_CCOMP建立两个等级的轮廓
cv2.RETR_TREE建立一个等级树结构的轮廓
method:
cv2.CHAIN_APPROX_NONE存储所有的轮廓点
cv2.CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息。
代码:
import cv2
import numpy as np
img = cv2.imread('shape.jpg') #读取图像
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
ret, binary = cv2.threshold(gray,220,255,cv2.THRESH_BINARY) #转为二值图
contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,\
cv2.CHAIN_APPROX_NONE) #寻找轮廓
n=len(contours) #轮廓个数
print(n)
print(len(contours[0])) #轮廓0像素数目
print(len(contours[1])) #轮廓1像素数目
print(len(contours[2])) #轮廓2像素数目
print(len(contours[3])) #轮廓3像素数目
2.绘制轮廓
代码如下:
cv2.imshow("img",img) #显示原图像
img2 = cv2.drawContours(img,contours,1,(0,165,255),-1) #绘制轮廓,1表示绘制第几个轮廓 -1是填充全部
cv2.imshow("contours",img2) #显示轮廓
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
3.逐一绘制轮廓
代码如下(示例):
n=len(contours) #轮廓个数
contoursImg=[]
for i in range(n):
temp=np.zeros(img.shape,np.uint8) #生成黑背景
contoursImg.append(temp)
contoursImg[i]=cv2.drawContours(contoursImg[i],contours,i,(255,255,255), 3) #绘制轮廓
cv2.imshow("contours[" + str(i)+"]",contoursImg[i]) #显示轮廓
cv2.waitKey()
cv2.destroyAllWindows()
4.实操
代码如下(示例):
import cv2
import numpy as np
img = cv2.imread('pig.jpg')
h,w = img.shape[:2]
img = cv2.resize(img,(int(w/2),int(h/2)))
cv2.imshow("img",img) #显示原图像
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度图
ret, binary = cv2.threshold(gray,245,255,cv2.THRESH_BINARY_INV) #转为二值图
cv2.imshow("binary" ,binary) #显示二值化结果
contours= cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE)[-2]#寻找轮廓
mask=np.zeros(img.shape,np.uint8) #生成黑背景,即全为0
mask=cv2.drawContours(mask,contours,-1,(255,255,255),-1) #绘制轮廓,形成掩膜
cv2.imshow("mask" ,mask) #显示掩膜
result=cv2.bitwise_and(img,mask) #按位与操作,得到掩膜区域
cv2.imshow("result" ,result) #显示图像中提取掩膜区域
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
三、使用矩特征计算轮廓的面积及长度
1.计算图像的矩特征
代码如下:
import cv2
import numpy as np
img = cv2.imread('shape.jpg') #读取图像
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
ret, binary = cv2.threshold(gray,220,255,cv2.THRESH_BINARY) #转为二值图
contours cv2.findContours(binary,cv2.RETR_TREE,\
cv2.CHAIN_APPROX_NONE)[-2] #寻找轮廓
n=len(contours) #轮廓个数
contoursImg=[]
for i in range(n):
temp=np.zeros(img.shape,np.uint8) #生成黑背景
contoursImg.append(temp)
contoursImg[i]=cv2.drawContours(contoursImg[i],contours,i,(255,255,255), 3) #绘制轮廓
cv2.imshow("contours[" + str(i)+"]",contoursImg[i]) #显示轮廓
print("计算图像的矩特征:")
for i in range(n):
moment=cv2.moments(contours[i])
print(f"轮廓{i}的矩:\n{moment}")
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
2.计算轮廓面积
代码如下:
import cv2
import numpy as np
img = cv2.imread('shape.jpg') #读取图像
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转为灰度值图
ret, binary = cv2.threshold(gray,220,255,cv2.THRESH_BINARY) #转为二值图
contours, hierarchy = cv2.findContours(binary,cv2.RETR_TREE,\
cv2.CHAIN_APPROX_NONE) #寻找轮廓
n=len(contours) #轮廓个数
contoursImg=[]
for i in range(n):
area = cv2.contourArea(contours[i])
print(f"轮廓{i}的面积:\n{area}")
四、使用Hu特征进行形状匹配
代码如下:
import cv2
o1 = cv2.imread('m1.png')
o2 = cv2.imread('m2.png')
o3 = cv2.imread('m3.png')
gray1 = cv2.cvtColor(o1,cv2.COLOR_BGR2GRAY)
gray2 = cv2.cvtColor(o2,cv2.COLOR_BGR2GRAY)
gray3 = cv2.cvtColor(o3,cv2.COLOR_BGR2GRAY)
ret, binary1 = cv2.threshold(gray1,127,255,cv2.THRESH_BINARY)
ret, binary2 = cv2.threshold(gray2,127,255,cv2.THRESH_BINARY)
ret, binary3 = cv2.threshold(gray3,127,255,cv2.THRESH_BINARY)
contours1, hierarchy = cv2.findContours(binary1,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
contours2, hierarchy = cv2.findContours(binary2,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
contours3, hierarchy = cv2.findContours(binary3,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
cnt1 = contours1[0]
cnt2 = contours2[0]
cnt3 = contours3[0]
ret0 = cv2.matchShapes(cnt1,cnt1,1,0.0)
ret1 = cv2.matchShapes(cnt1,cnt2,1,0.0)
ret2 = cv2.matchShapes(cnt1,cnt3,1,0.0)
print("相同图像的 matchShape=",ret0)
print("相似图像的 matchShape=",ret1)
print("不相似图像的 matchShape=",ret2)
五、轮廓拟合
1.矩形包围框
代码如下:
import cv2
img=cv2.imread('shape.jpg')
cv2.imshow("original",img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) [-2]
x,y,w,h=cv2.boundingRect(contours[0])
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,0),2)
cv2.imshow("result",img)
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
2.最小包围矩形框
代码如下:
import cv2
o=cv2.imread('shape.jpg')
cv2.imshow("original",o)
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2]
rect = cv2.minAreaRect(contours[1])
print("返回值 rect:\n",rect)
points = cv2.boxPoints(rect)
print("\n 转换后的 points:\n",points)
points = np.int64(points) #取整,np.int64=np.int0
image=cv2.drawContours(o,[points],0,(0,0,0),2)
cv2.imshow("result",o)
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
3.最小包围圆形
代码如下:
import cv2
o=cv2.imread('shape.jpg')
cv2.imshow("original",o)
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours= cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2]
(x,y),radius = cv2.minEnclosingCircle(contours[1])
center = (int(x),int(y))
radius = int(radius)
cv2.circle(o,center,radius,(0,0,0),2) # 跟 matplotlib 类似吧。。
cv2.imshow("result",o)
cv2.waitKey()
cv2.destroyAllWindows()
4.最优拟合椭圆
代码如下:
import cv2
o=cv2.imread('shape.jpg')
cv2.imshow("original",o)
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours= cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2]
ellipse = cv2.fitEllipse(contours[1])
print("ellipse=",ellipse)
cv2.ellipse(o,ellipse,(0,255,0),3)
cv2.imshow("result",o)
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
5.最优拟合直线
代码如下:
import cv2
o=cv2.imread('shape.jpg')
cv2.imshow("original",o)
gray = cv2.cvtColor(o,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours= cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2]
rows,cols = o.shape[:2]
[vx,vy,x,y] = cv2.fitLine(contours[1], cv2.DIST_L2,0,0.01,0.01) # 返回值是共线的归一化向量,和线上一点
lefty = int((-x*vy/vx) + y) # 说白了就是一个方向和一个点,点斜式嘛,还啥vec4f,,讲究
righty = int(((cols-x)*vy/vx)+y) # 计算两个点,代值计算就行
cv2.line(o,(cols-1,righty),(0,lefty),(0,255,0),2)
cv2.imshow("result",o)
cv2.waitKey()
cv2.destroyAllWindows()
代码效果如下:
6.逼近多边形
代码如下:
import cv2
import numpy as np
# 多边形逼近
# 1.先找到轮廓
img = cv2.imread('contours3.png')
cv2.imshow("original",img)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
contours= cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[-2]
cnt = contours[0]
# 2.进行多边形逼近,得到多边形的角点
approx1 = cv2.approxPolyDP(cnt, 3, True)
approx2 = cv2.approxPolyDP(cnt, 15, True)
approx3 = cv2.approxPolyDP(cnt, 75, True)
# 3.画出多边形
adp=img.copy()
img1=cv2.polylines(adp, [approx1], True, (255, 0, 0), 2)
cv2.imshow('approxPloyDP1', img1)
####
adp=img.copy()
img2=cv2.polylines(adp, [approx2], True, (0, 255, 0), 2)
cv2.imshow('approxPloyDP2', img2)
#####
adp=img.copy()
img3=cv2.polylines(adp, [approx3], True, (0, 0, 255), 2)
cv2.imshow('approxPloyDP3', img3)
print(len(approx1),len(approx2),len(approx3)) # 角点的个数
cv2.waitKey(0)
cv2.destroyAllWindows()
代码效果如下:
总结
提示:这里对文章进行总结:图像轮廓知识点非常的多,一般就是用FInd寻找轮廓然后Draw画轮廓。