Python-OpenCV 图像处理(二十一):对象测量

import cv2
import numpy as np
from matplotlib import pyplot as plt

__author__ = "zxsuperstar"
__email__ = "[email protected]"

"""
对象测量
轮廓发现,计算每个轮廓的弧长和面积

多边形拟合
获取多边形拟合结果
approxPolyDP
    contour
    epsilon越小越折线逼近真实形状
    close 是否为闭合区域
"""
def measure_object(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGRA2GRAY)
    ret, binary = cv2.threshold(gray, 0 ,255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)
    cv2.imshow("binary", binary)
    # cv2.waitKey(0)
    outimage, contours, heriachy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for i, contour in enumerate(contours):
        area = cv2.contourArea(contour)#计算轮廓面积
        #外接矩形大小
        x, y, w, h = cv2.boundingRect(contour)
        rate = min(w,h)/max(w,h) #宽高比
        # 几何距
        mm = cv2.moments(contour) #返回值字典类型
        cx = mm["m10"]/mm["m00"]
        cy = mm["m01"]/mm["m00"]
        # cv2.circle(image, (np.int(cx),np.int(cy)), 2,(0,255,255),-1)
        # cv2.rectangle(image, (x,y),(x+w, y+h),(0,0,255), 2)
        cv2.circle(binary, (np.int(cx), np.int(cy)), 2, (0, 255, 255), -1)
        # cv2.rectangle(binary, (x, y), (x + w, y + h), (0, 0, 255), 2)
        print("area:",area)
        approx = cv2.approxPolyDP(contour,4,True)
        if approx.shape[0] > 10: #几何形状 边
            cv2.drawContours(binary, contours, i, (0,255,0), 2)
    cv2.imshow("contours", image)


if __name__ == "__main__":
    image = cv2.imread("11.jpg") #blue green red

    # img = cv2.resize(src, (0, 0), fx=0.25, fy=0.25, interpolation=cv2.INTER_NEAREST)
    # h,w,_ = img.shape
    # print(img.shape)
    # image = img[20:h - 20, 20:w - 20]
    measure_object(image)
    # print(image.shape)
    # cv2.imshow("image",image)

    cv2.waitKey(0)
    cv2.destroyAllWindows()


运行结果:

猜你喜欢

转载自blog.csdn.net/zx_good_night/article/details/88719510