Python+opencv 对象测量

1、弧长与面积

a、轮廓发现

b、计算每个轮廓的弧长与面积,以像素为单位

2、多边形拟合

a、获取轮廓的多边形拟合效果

b、approxPolyDP(contour,epsilon,close)

epsilon越小,折线越逼近真实形状。close决定是否为闭合区域

3、几何矩计算

a、原点矩    Mpq = \sum_{x=1}^{M}\sum_{y=1}^{N}x^{p}y^{q}f(x,y)

b、中心矩 \mu _{pq}=\sum_{x=1}^{M}\sum_{y=1}^{N}(x-x_{0})^{p}(y-y_{0})^{q}f(x,y)

那么图像的重心坐标是x_{c}=\frac{M_{10}}{M_{00}}y_{c}=\frac{M_{01}}{M_{00}}

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()

 

第三幅图中黄色的圆点就是数字的重心。

发布了70 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Acmer_future_victor/article/details/104153886