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

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

__author__ = "zxsuperstar"
__email__ = "zxsuperstar@163.com"

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

多边形拟合
获取多边形拟合结果
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()


运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值