弧长与面积
轮廓发现
计算每个轮廓的弧长与面积,像素单位
多边形拟合
获取轮廓的多边形拟合结果
approxPolyDP():contour、epsilon越小越折线越逼近真实形状、close是否为闭合区域
API参考:https://www.jianshu.com/p/0205c963104d
几何矩计算
视频源码:
import cv2 as cv
import numpy as np
def measure_object(image):
# 先弱化一下噪声,如果轮廓识别时识别到了噪声,因为噪声尺寸都很小,会导致其轮廓也极小(两三个像素点),结果是几何矩为0,计算重心时会除0报错
image = cv.GaussianBlur(image, (3, 3), 0)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
print("threshold value : {}".format(ret))
cv.imshow("binary image", binary)
dst = cv.cvtColor(binary, cv.COLOR_GRAY2BGR)
# 这一步是找轮廓,因为测量对象轮廓往往只是想测量对象最外部的轮廓,所以这里第二个参数选cv.RETR_EXTERNAL
contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# 计算轮廓面积、获取轮廓外接矩形、计算轮廓几何矩、根据几何矩算重心、在原图上画重心和外接矩形
for i, contour in enumerate(contours):
area = cv.contourArea(contour) # area 是 cv.contourArea(contour) 计算contour轮廓的面积
rect_x, rect_y, rect_w, rect_h = cv.boundingRect(contour) # rect 是 contour 这个轮廓的外接矩形
rate = min(rect_w, rect_h) / max(rect_w, rect_h) # 计算一个数字的rect的横纵比
print("rectangle rate : {}".format(rate))
mm = cv.moments(contour) # 计算 contour 的几何矩
print(type(mm)) # mm 是一个字典类型
cx = mm['m10'] / mm['m00'] # cx、cy是图像重心
cy = mm['m01'] / mm['m00']
cv.circle(dst, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -1) # 把该轮廓的重心画出来
cv.rectangle(dst, (rect_x, rect_y), (rect_x + rect_w, rect_y + rect_h), (0, 0, 255), 2)
print("contour area {}".format(area))
# 多边形逼近
approxCurve = cv.approxPolyDP(contour, 4, True)
print(approxCurve.shape)
if approxCurve.shape[0] > 10: # 如果该轮廓的边数大于10(一般是圆或椭圆),则把轮廓画出来,这样可以区分正方形、三角形等多边形
cv.drawContours(dst, contours, i, (0, 255, 0), 2)
cv.imshow("measure contours", dst)
print("-----------Python OpenCV Tutorial--------------")
src = cv.imread("C:/cv-samples/data/handwritten_numeral.jpg")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
measure_object(src)
cv.waitKey(0)
cv.destroyAllWindows()