1、弧长与面积
a、轮廓发现
b、计算每个轮廓的弧长与面积,以像素为单位
2、多边形拟合
a、获取轮廓的多边形拟合效果
b、approxPolyDP(contour,epsilon,close)
epsilon越小,折线越逼近真实形状。close决定是否为闭合区域
3、几何矩计算
import cv2 as cv
import numpy as np
def measure_object(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
print('threshold value: %s' % ret)
cv.imshow('binary image', binary)
dst = cv.cvtColor(binary, cv.COLOR_GRAY2BGR)
contours, hireachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
# 边缘面积
area = cv.contourArea(contour)
# 外接矩形
x, y, w, h = cv.boundingRect(contour)
# 宽高比 1的宽高比最小
rate = min(w, h) / max(w, h)
print('rectangle rate: %s' % rate)
# 几何矩
mm = cv.moments(contour)
# mm是一个字典
print(type(mm))
cx = mm['m10']/mm['m00']
cy = mm['m01']/mm['m00']
cv.circle(image, (np.int(cx), np.int(cy)), 2, (0, 255, 255), -1)
# cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 2)
print('contour area %s' % area)
approxCurve = cv.approxPolyDP(contour, 4, True)
print(approxCurve.shape)
# 绘制多边形来拟合,多边形边数大于10
if approxCurve.shape[0] > 10:
cv.drawContours(dst, contours, i, (0, 255, 0), 2)
# 绘制四边形,多边形拟合时边数恒等于4
if approxCurve.shape[0] == 4:
cv.drawContours(dst, contours, i, (0, 255, 0), 2)
# 绘制三角形,多边形边数恒等于3
if approxCurve.shape[0] == 3:
cv.drawContours(dst, contours, i, (0, 255, 0), 2)
cv.imshow('measure-contours', image)
src = cv.imread('C:/Users/Y/Pictures/Saved Pictures/digits.jpg')
cv.namedWindow('input image', cv.WINDOW_AUTOSIZE)
cv.imshow('input image', src)
measure_object(src)
cv.waitKey(0)
cv.destroyAllWindows()
第三幅图中黄色的圆点就是数字的重心。