OpenCV Python学习笔记(11)—— 对象测量

1 弧长和面积

计算每个轮廓的弧长和面积,单位是像素

2 多边形拟合

approxPolyDP

  • contour
  • epsilon 越小,折现越逼近真实形状
  • close:是否为闭合区域

3 几何矩的计算

OpenCV Python学习笔记(11)—— 对象测量_第1张图片

4 算面积

import cv2 as cv
import numpy as np


def measure_demo(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)
    outImage, 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)
        mm = cv.moments(contour)
        type(mm)
        cx = mm['m10'] / mm['m00']
        cy = mm['m01'] / mm['m00']
        cv.circle(image, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -1)
        cv.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
        print("contour area %s" % area)
    cv.imshow("measure-contours", image)


src = cv.imread("resource/num.png")
cv.namedWindow("Test", cv.WINDOW_AUTOSIZE)
cv.imshow("Test", src)
measure_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()

OpenCV Python学习笔记(11)—— 对象测量_第2张图片
OpenCV Python学习笔记(11)—— 对象测量_第3张图片
OpenCV Python学习笔记(11)—— 对象测量_第4张图片
OpenCV Python学习笔记(11)—— 对象测量_第5张图片

5 检测不同的几何形状

import cv2 as cv
import numpy as np


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

    outImage, 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)

        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']

        # 3:点的半径;下一个参数:颜色; -1:填充
       # cv.circle(dst, (np.int(cx), np.int(cy)), 3, (0, 255, 255), -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)
        print(approxCurve.shape)

        # 大于6条小线段,是圆
        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)

    cv.imshow("measure-contours", dst)


src = cv.imread("resource/lk.png")
cv.namedWindow("Test", cv.WINDOW_AUTOSIZE)
cv.imshow("Test", src)
measure_demo(src)
cv.waitKey(0)
cv.destroyAllWindows()

OpenCV Python学习笔记(11)—— 对象测量_第6张图片
OpenCV Python学习笔记(11)—— 对象测量_第7张图片

你可能感兴趣的:(数字图像处理Java学习笔记)