OpenCV图像处理技术(Python)——图像轮廓

© Fu Xianjun. All Rights Reserved.

一、什么是图像轮廓?

图像轮廓指的是将边缘连接起来形成一个整体,用于后续的计算。

二、查找并绘制轮廓

1.查找轮廓

·语法格式:
image,contours,hierarchy = cv2.findContours(image,mode,method)
式中返回值为:
·image: 与函数参数中的原始图像image一致。
·contours 返回的轮廓。
·hierarchy 图像的拓扑信息(轮廓层次)。
式中参数为:
·mode: 轮廓检索模式。
·method: 轮廓的近似方法。
参数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.绘制轮廓

语法格式:
image = cv2.drawContours(scr,contours,-1,color,thickness)
代码如下:

import cv2
import numpy as np
cv2.imshow("img",img) #显示原图像
img2 = cv2.drawContours(img,contours,1,(0,165,255),-1)  #绘制轮廓,1表示绘制第几个轮廓
cv2.imshow("contours",img2)   #显示轮廓
cv2.waitKey()
cv2.destroyAllWindows()

结果如下:
在这里插入图片描述

三、矩特征

1.矩的计算

作用: 获取图像moments特征,可以方便的比较两个轮廓。
语法格式:
retval = cv2.moments(array[,bianryImage])
·array: 可以是点集,也可以是灰度图像或者二值图像。当array是点集时,函数会把这些点集当成轮廓中的顶点,把整个点集作为一条轮廓,而不是把它们当成独立的点来看。
·binaryImage: 该参数为True时,array内所有的非零值都被处理为1.该参数仅在参数array为图像时有效。

代码如下:

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):
    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.计算轮廓的面积

语法格式: retval = cv2.contourArea(contour[,oriented])
· contour是轮廓。
· oriented是布尔型值。当它是True时,返回的值包含正\负号,用来表示轮廓是顺时针还是逆时针。该参数的默认值是False,表示返回的retval是一个绝对值。
代码如下:

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}")

3.计算轮廓的长度

语法格式: retval = cv2.arcLength(curve,closed)
· curve是轮廓
· closed是布尔值型,用来表示轮廓是否封闭。该值为True时,表示轮廓时封闭的。
代码如下:

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):
    length = cv2.arcLength(contours[i], True)  #获取轮廓长度
    print(f"轮廓{i}的长度:\n{length}")

四、Hu矩

1.Hu矩函数

语法格式: hu = cv2.HuMoments(m)
· 参数m,是由函数cv2.moments()计算得到矩特征值。
函数cv2.moments()返回的归一化中心矩中包含:
· 二阶Hu矩: nu20,nu11,nu02
· 三阶Hu矩: nu30,nu21,nu12,nu03

2.形状匹配

代码如下:

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, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) 
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
import numpy as np
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, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE) 
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
import numpy as np
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, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

(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
import numpy as np
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, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

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
import numpy as np
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, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

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, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
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()

结果如下:
在这里插入图片描述

六、总结

cv2.findContours()是本章学习的中心代码,图像轮廓的运用非常广阔,像信用卡识别、图片检测等待斗艳用到cv2.findContours函数。


版权声明:本文为weixin_52243766原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。