OpenCV python 轮廓面积与凸包面积比

OpenCV python 轮廓面积与凸包面积比

处理图片:[hand.jpg]
OpenCV python 轮廓面积与凸包面积比_第1张图片

import cv2


def get_contours(img):
    """获取连通域

    :param img: 输入图片
    :return: 最大连通域
    """
    # 灰度化, 二值化, 连通域分析
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    ret, img_bin = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)

    img_contour, contours, hierarchy = cv2.findContours(img_bin, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)

    return contours[0]


def main():
    # 1.导入图片
    img_src = cv2.imread("hand.jpg")
    img_result = img_src.copy()

    # 2.获取连通域
    cont = get_contours(img_src)
    cv2.drawContours(img_result, cont, -1, (0, 0, 255), 2)

    # 3.获取凸包点
    hull_points = cv2.convexHull(cont)
    cv2.polylines(img_result, [hull_points], True, (0, 255, 0), 2)

    # 4.计算 轮廓面积 与 凸包面积
    cnt_area = cv2.contourArea(cont)
    hull_area = cv2.contourArea(hull_points)
    print("轮廓面积=", cnt_area)
    print("凸包面积=", hull_area)

    # 5.计算 轮廓面积/凸包面积
    solidity = float(cnt_area) / hull_area
    print("solidity = %.4f" % solidity)

    # 6.显示结果
    cv2.imshow("img_result", img_result)

    cv2.waitKey()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()

结果图片[img_result.jpg]
OpenCV python 轮廓面积与凸包面积比_第2张图片

你可能感兴趣的:(Opencv-python)