【OpenCV-Python】17.OpenCV的图像轮廓——轮廓特征

17.OpenCV的图像轮廓——轮廓特征



前言

  图像轮廓是指由位于边缘、连续的、具有相同颜色和强度的点构成的曲线,它可以用于形状分析以及对象检测和识别。


一、轮廓的矩

  轮廓的矩包含了轮廓的各种几何特征,如面积、位置、角度、形状等。cv2.moments()函数用于返回轮廓的矩,其基本格式如下:

ret = cv2.moments(array[, binaryImage])

ret为返回的轮廓的矩,是一个字典对象, 大多数矩的含义比较抽象, 但其中的零阶矩(m00)表示轮廓的面积
array为表示轮廓的数组
binaryImage值为True,会将array对象中的所有非0值设置为1
import cv2
import numpy as np
import matplotlib.pyplot as plt

img = cv2.imread('shape2.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255

img1 = cv2.drawContours(img1, contours, -1,(0,255,0),2)
cv2.imshow('Contours',img1)

m0 = cv2.moments(contours[0])
m1 = cv2.moments(contours[1])

print('轮廓0的矩:', m0)
print('轮廓1的矩:', m1)

print('轮廓0的面积:', m0['m00'])
print('轮廓1的面积:', m1['m00'])

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述
在这里插入图片描述


二、轮廓的面积

  cv2.contourArea()函数用于返回轮廓的面积,其基本格式如下:

ret = cv2.contourArea(contour[, oriented])

ret为返回的面积
contour为轮廓
oriented为可选参数, 其参数值为True, 返回值的正与负表示表示轮廓是顺时针还是逆时针, 参数值为False(默认值), 函数返回值为绝对值
img = cv2.imread('shape2.jpg')

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

m0 = cv2.contourArea(contours[0])
m1 = cv2.contourArea(contours[1])

print('轮廓0的面积:', m0)
print('轮廓1的面积:', m1)

在这里插入图片描述


三、轮廓的长度

  cv2.arcLength()函数用于返回轮廓的长度,其基本格式如下:

ret = cv2.cv2.arcLength(contour, closed)

ret为返回的长度
contour为轮廓
closed为布尔值,True时表示轮廓是封闭的
img = cv2.imread('shape2.jpg')

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

m0 = cv2.arcLength(contours[0], True)
m1 = cv2.arcLength(contours[1], True)

print('轮廓0的长度:', m0)
print('轮廓1的长度:', m1)

在这里插入图片描述


四、轮廓的近似多边形

  cv2.approxPolyDP()函数用于返回轮廓的近似多边形,其基本格式如下:

ret = cv2.cv2.arcLength(contour, epsilon, closed)

ret为返回的近似多边形
contour为轮廓
epsilon为精度, 表示近似多边形接近轮廓的最大距离
closed为布尔值,True时表示轮廓是封闭的
img = cv2.imread('shape3.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255
img1 = cv2.drawContours(img1, contours, -1, (0,0,255), 2)
cv2.imshow('Contours',img1)

arcl = cv2.arcLength(contours[0], True)

img2 = img1.copy()
app = cv2.approxPolyDP(contours[0], arcl*0.05, True)
img2 = cv2.drawContours(img2, [app], -1, (255,0,0), 2)
cv2.imshow('contours',img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述


五、轮廓的凸包

  cv2.convexHull()函数用于返回轮廓的凸包,其基本格式如下:

hull = cv2.convexHull(contours[, clockwise[, returnPointss]])

hull为返回的凸包, 是一个numpy.ndarray对象, 包含了凸包的关键点
contours为轮廓
clockwise为方向标记,True, 凸包为顺时针方向,False(默认值)时, 凸包为逆时针方向
returnPointss为True(默认值), 返回的hull中包含的是凸包关键点的坐标,False, 返回的是凸包关键点在轮廓中的索引
img = cv2.imread('shape3.jpg')

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255
img1 = cv2.drawContours(img1, contours, -1, (0,0,255), 2)
cv2.imshow('Contours',img1)

hull = cv2.convexHull(contours[0])
print('returnPoints = Treu 时返回的凸包;n',hull)

hull2 = cv2.convexHull(contours[0], returnPoints=False)
print('returnPoints = False时返回的凸包;n',hull2)

cv2.polylines(img1, [hull], True, (255,0,0),2)
cv2.imshow('ConvecHull',img1)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述
在这里插入图片描述


六、轮廓的直边界矩形

  轮廓的直边界矩形是指可容纳轮廓的矩形,且矩形的两条边必须是平行的,直边界矩形不一定是面积最小的边界矩形。
  cv2.boundingRect()函数用于返回轮廓的直边界矩形,其基本格式如下:

ret = cv2.boundingRect(contours)

ret为返回的直边界矩形, 它是一个四元组, 其格式为(矩形左上角x坐标, 矩形左上角y坐标, 矩形的宽度, 矩形的高度)
contours为用于计算直边界矩形的轮廓
img = cv2.imread('shape4.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255

img1 = cv2.drawContours(img1, contours, -1, (0,0,255), 2)
cv2.imshow('Contours',img1)

ret = cv2.boundingRect(contours[0])
print('直边界矩形:n', ret)

pt1 = (ret[0], ret[1])
pt2 = (ret[0] + ret[2], ret[1] + ret[3])
img2 = img1.copy()
img2 = cv2.rectangle(img2, pt1, pt2, (255,0,0), 1)
cv2.imshow('Rectangle', img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述
在这里插入图片描述


七、轮廓的旋转矩形

  轮廓的旋转矩形是指可容纳轮廓的面积最小的矩形。
  cv2.minAreaRect()函数用于返回轮廓的旋转矩形,其基本格式如下:

box = cv2.minAreaRect(contour)

box为返回的旋转矩阵, 它是一个三元组, 其格式为((矩形中心点x坐标, 矩形中心点y坐标), (矩形的宽度, 矩形的高度), 矩形的旋转角度)
contour为用于计算矩形的轮廓

  cv2.minAreaRect()函数返回的结果不能直接用于绘制旋转矩形,可以使用cv2.boxPoints()函数将其转换为矩形的顶点坐标,其基本格式如下:

points = cv2.boxPoints(box)

points为返回的矩形顶点坐标, 坐标数据为浮点数
box为cv2.minAreaRect()函数返回的矩形数据
img = cv2.imread('shape4.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255
cv2.drawContours(img1, contours, -1, (0,0,255) ,2)
cv2.imshow('Contours',img1)

# 计算最小旋转矩形
ret = cv2.minAreaRect(contours[0])
rect = cv2.boxPoints(ret)
rect = np.int0(rect)

img2 = img1.copy()
cv2.drawContours(img2, [rect], 0, (255,0,0), 2)
cv2.imshow('Rectangle', img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述


八、轮廓的最小外包圆

  cv2.minEnclosingCircle()函数用于返回可容纳轮廓的最小外包圆,其基本格式如下:

center, radius = cv2.minEnclosingCircle(contours)

center为圆心
radius为半径
contours为用于计算最小外包圆的轮廓
img = cv2.imread('shape4.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255
cv2.drawContours(img1, contours, -1, (0,0,255) ,2)
cv2.imshow('Contours',img1)

# 计算最小外包圆
(x, y), radius = cv2.minEnclosingCircle(contours[0])
center = (int(x),int(y))
radius = int(radius)

img2 = img1.copy()
cv2.circle(img2, center, radius, (255,0,0),2)
cv2.imshow('Circle',img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述


九、轮廓的拟合椭圆

  cv2.fitEllipse()函数用于返回轮廓的拟合椭圆,其基本格式如下:

ellipse = cv2.fitEllipse(contours)

ellipse为返回的椭圆
contours为用于计算拟合椭圆的轮廓
img = cv2.imread('shape4.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255
cv2.drawContours(img1, contours, -1, (0,0,255) ,2)
cv2.imshow('Contours',img1)

# 计算拟合椭圆
ellipse = cv2.fitEllipse(contours[0])

img2 = img1.copy()
cv2.ellipse(img2, ellipse, (255,0,0),2)
cv2.imshow('Circle',img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述


十、轮廓的拟合直线

  cv2.fitLine()函数用于返回轮廓的拟合直线,其基本格式如下:

line = cv2.fitLine(contours, distType, param, reps, aeps)

line为返回的拟合直线
contours为用于计算拟合直线的轮廓
distType为距离参数类型, 决定如何计算拟合直线
param为距离参数, 与距离参数类型有关, 其设置为0, 函数将自动选择最优值
reps为计算拟合直线需要的径向精度, 通常设置为0.01
aeps为计算拟合直线需要的轴向精度, 通常设置为0.01

  param距离参数类型:

param 说明
cv2.DIST_USER 用户自定义距离
cv2.DIST_L1 用2个点的坐标计算计算距离, 公式为|x1-x2|+|y1-y2|
cv2.DIST_L2 欧氏距离(两个点的直线距离)
cv2.DIST_C 用2个点的坐标计算计算距离, 公式为max(|x1-x2|,|y1-y2|)
cv2.DIST_L12 用1个点的坐标计算计算距离, 公式为2(sqrt(1+x*x/2)-1)
cv2.DIST_FAIR 用1个点的坐标计算计算距离, 公式为c^2(|x|/c-log(1+|x|/c)), c=1.3998
cv2.DIST_WELSCH 用1个点的坐标计算计算距离, 公式为c^2/2(1-exp(-(x/c)^2), c=2.9846
cv2.DIST_HUBER 用1个点的坐标计算计算距离, 公式为|x|<c?x^2/2:c(|x|-c/2), c=1.345
img = cv2.imread('shape4.jpg')            
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255      
cv2.drawContours(img1, contours, -1, (0,0,255), 2)
cv2.imshow('Contours',img1)

#计算拟合直线
img2 = img1.copy()
rows, cols = img.shape[:2]
[vx, vy, x, y] = cv2.fitLine(contours[0], cv2.DIST_L1, 0, 0.01, 0.01)
lefty = int((-x * vy / vx) + y)
righty = int(((cols - x) * vy / vx) + y)
cv2.line(img2, (0, lefty), (cols-1, righty), (255,0,0), 2)   

cv2.imshow('FitLine',img2)  
cv2.waitKey(0)
cv2.destroyAllWindows()   

在这里插入图片描述


十一、轮廓的最小外包三角形

  cv2.minEnclosingTriangle()函数用于返回可容纳轮廓的最小外包三角形,其基本格式如下:

retval, triangle = cv2.minEnclosingTriangle(contours)

retval为最小外包三角形的面积
triangle为最小外包三角形
contours为用于计算最小外包三角形的轮廓
img = cv2.imread('shape4.jpg')
cv2.imshow('original', img)

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

ret, thresh = cv2.threshold(img_gray, 125, 255, cv2.THRESH_BINARY)

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img1 = np.zeros(img.shape, np.uint8) + 255
cv2.drawContours(img1, contours, -1, (0,0,255) ,2)
cv2.imshow('Contours',img1)

# 计算最小外包三角形
retval, triangle = cv2.minEnclosingTriangle(contours[0])
triangle = np.int0(triangle)

img2 = img1.copy()
cv2.polylines(img2, [triangle], True, (255,0,0),2)
cv2.imshow('Triangle',img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

在这里插入图片描述


十二、OpenCV-Python资源下载

OpenCV-Python测试用图片、中文官方文档、opencv-4.5.4源码


总结

  以上内容介绍了OpenCV-Python的轮廓特征,有关Python、数据科学、人工智能等文章后续会不定期发布,请大家多多关注,一键三连哟(●’◡’●)。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>