[3] opencv: python求图像上多条曲线中最长及最短曲线

opecv计算轮廓,各阶矩,轮廓面积; 通过面积近似得到较长的曲线

原始输入图片: blackline.jpg
计算图像中最长与最短曲线,并获取其重心坐标。
[3] opencv: python求图像上多条曲线中最长及最短曲线_第1张图片

代码:
import cv2
import numpy as np


def calc_coordinate_area(contour):
    M = cv2.moments(contour)  # 计算轮廓的各阶矩,字典
    # print(M)
    # 计算重心
    cx = int(M['m10'] / M['m00'])
    cy = int(M['m01'] / M['m00'])
    # 计算轮廓面积
    area = cv2.contourArea(contour)
    print('cx:%f, cy:%f, area:%f' % (cx, cy, area))
    return cx, cy, area


def main():
    img0 = cv2.imread('blackline.jpg')
    img = img0.copy()

    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    img = cv2.dilate(img, kernel, iterations=1)

    ret, thresh = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 127, 255, 0)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)  # 得到轮廓信息
    print(len(contours))

    areas = []
    coordinate = []
    for i in range(len(contours)):
        cx, cy, area = calc_coordinate_area(contours[i])
        areas.append(area)
        coordinate.append([cx, cy])
    print(areas)
    areas_np = np.array(areas)
    max_idx = np.argmax(areas_np)  # 得到最长路径索引
    min_idx = np.argmin(areas_np)  # 得到最短路径索引
    print("max: %d, min: %d" % (max_idx, min_idx))
    imgnew = cv2.drawContours(img, contours[max_idx], -1, (0, 255, 0), 1)  # 画出最长路径
    imgnew = cv2.drawContours(imgnew, contours[min_idx], -1, (0, 0, 255), 1)  # 画出最段路径
    print(coordinate[max_idx]) # 最长路径重心坐标
    print(coordinate[min_idx]) # 最短路径重心坐标
    cv2.circle(imgnew, tuple(coordinate[max_idx]), 3, (0, 255, 0), 3)  # 画出最长路径重心坐标
    cv2.circle(imgnew, tuple(coordinate[min_idx]), 3, (0, 0, 255), 3)  # 画出最短路径重心坐标

    cv2.imshow('img0', img0)
    # cv2.imshow('thresh', thresh)
    cv2.imshow('imgnew', imgnew)
    cv2.imwrite('imgnew_result.jpg', imgnew)
    cv2.waitKey(0)


if __name__ == '__main__':
    main()
结果:

3
cx:299.000000, cy:172.000000, area:683.000000
cx:125.000000, cy:165.000000, area:1136.500000
cx:218.000000, cy:181.000000, area:1817.000000
[683.0, 1136.5, 1817.0]
max: 2, min: 0
[218, 181]
[299, 172]

绘制结果图片:
[3] opencv: python求图像上多条曲线中最长及最短曲线_第2张图片

参考大佬的博文(对矩的解释):
https://blog.csdn.net/qq826309057/article/details/70039397?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

[3] opencv: python求图像上多条曲线中最长及最短曲线_第3张图片

你可能感兴趣的:(opencv,python,opencv)