Python+OpenCV入门教程【十五】轮廓发现及对象测量

轮廓发现:当通过阈值分割提取到图像中的目标物体后,就需要通过边缘检测来提取目标物体的轮廓,使用这两种方法基本能够确定物体的边缘或者前景。接下来,通常需要做的是拟合这些边缘的前景,如拟合出包含前景或者边缘像素点的最小外包矩形、圆、凸包等几何形状,为计算它们的面积或者模板匹配等操作打下坚实的基础。

对象测量:opencv 中轮廓特征包括:如面积,周长,质心,边界框等。

findContours()与drawContours()详解点击此处

下面展示 代码

import cv2 as cv
import numpy as np

# 边缘检测
def edge_demo(image):
    blurred = cv.GaussianBlur(image, (9, 9), 5)
    gray = cv.cvtColor(blurred, cv.COLOR_BGR2GRAY)
    # X Gradient
    xgrad = cv.Sobel(gray, cv.CV_16SC1, 1, 0)
    # Y Gradient
    ygrad = cv.Sobel(gray, cv.CV_16SC1, 0, 1)
    #edge
    #edge_output = cv.Canny(xgrad, ygrad, 50, 150)
    edge_output = cv.Canny(gray, 30, 100)
    cv.imshow("Canny Edge", edge_output)
    return edge_output

# 轮廓发现
def contours_demo(image):
    # 高斯模糊  去噪
    dst = cv.GaussianBlur(image, (3, 3), 0)
    # 转灰度图
    gray = cv.cvtColor(dst, cv.COLOR_BGR2GRAY)
    # 二值化图像
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    cv.imshow("binary image", binary)#直接二值化的图像
    #binary = edge_demo(image)   #过边缘处理后的图像
    #可以是直接二值化的图像也可以是经过边缘处理后的图像(两种方法视情况而定)

    # 找轮廓
    #cloneImage, contours, heriachy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
    contours, hierarchy = cv.findContours(binary,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    # 绘制轮廓
    cv.drawContours(image,contours,-1,(0,0,255),3)
    cv.imshow("detect contours", image)

# 对象测量
def measure_object(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    print("threshold value : %s" % ret)
    cv.imshow("binary image", binary)
    dst = cv.cvtColor(binary, cv.COLOR_GRAY2BGR)
    contours, hierarchy = 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)  # 轮廓的外接矩形
        rate = min(w, h) / max(w, h)  # 轮廓外接矩形的宽高比
        print("rectangle rate : %s" % rate)
        mm = cv.moments(contour)  # 求轮廓的几何矩
        # print(type(mm))#字典型数据
        cx = mm['m10'] / mm['m00']  # 原点的零阶矩
        cy = mm['m01'] / mm['m00']
        cv.circle(dst, (np.int(cx), np.int(cy)), 3, (0, 0, 255), -1)  ##画出中心点,-1表示填充
        # cv.rectangle(dst, (x, y), (x+w, y+h), (0, 0, 255), 2)#绘制轮廓的外接矩形
        print("contour area %s" % area)
        approxCurve = cv.approxPolyDP(contour, 4, True)  # 多边形逼近 4是与阈值的间隔大小,越小越易找出,True是是否找闭合图像
        """
        cv.contourArea(contour)      #获取每个轮廓面积
        cv.boundingRect(contour)     #获取轮廓的外接矩形
        cv.moments(contour)          #求取轮廓的几何距
        cv.arcLength(contour,True)  #求取轮廓的周长,指定闭合
        approxPolyDP(curve, epsilon, closed, approxCurve=None)
       第一个参数curve:输入的点集,直接使用轮廓点集contour
       第二个参数epsilon:指定的精度,也即是原始曲线与近似曲线之间的最大距离。
       第三个参数closed:若为true,则说明近似曲线是闭合的,反之,若为false,则断开。
       第四个参数approxCurve:输出的点集,当前点集是能最小包容指定点集的。画出来即是一个多边形;

       print(approxCurve)  #打印每个轮廓的特征点
       print(approxCurve.shape)  #打印该点集的shape,第一个数是代表了点的个数,也就是边长连接逼近数
        """
        print(approxCurve.shape)
        if approxCurve.shape[0] > 6:
            cv.drawContours(dst, contours, i, (0, 255, 0), 2)
        if approxCurve.shape[0] == 4:
            cv.drawContours(dst, contours, i, (0, 0, 255), 2)
        if approxCurve.shape[0] == 3:
            cv.drawContours(dst, contours, i, (255, 0, 0), 2)
    cv.imshow("measure-contours", dst)
    cv.imshow("measure-contours", dst)



if __name__ == '__main__':
    '''
    轮廓发现contours_demo()
    '''
    # src = cv.imread("data/coins.jpg")
    # cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
    # cv.imshow("input image", src)
    # contours_demo(src)
    # cv.waitKey(0)
    # cv.destroyAllWindows()

    '''
    对象测量measure_object()
    '''
    src = cv.imread("data/shape.jpg")
    cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
    cv.imshow("input image", src)
    measure_object(src)
    cv.waitKey(0)

    cv.destroyAllWindows()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

缄默:)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值