Opencv提取点集合的凸包及外界轮廓

import cv2 as cv
import numpy as np
import random
import time

random.seed(time.time())
print(time.time())

if __name__=='__main__':

    img_gray = np.zeros((500, 600), dtype=np.uint8)

    #生成点
    pts = []
    for i in range(0, 100):
        rx = random.randint(100, 500)
        ry = random.randint(100, 400)
        pts.append([rx, ry])
        cv.line(img_gray, (rx, ry), (rx, ry), 255)
    cv.imshow('points', img_gray)

    #寻找最大凸包
    pts = np.array(pts)
    hull = cv.convexHull(pts, clockwise=True, returnPoints=True)
    length = len(hull)
    for i in range(length):
        cv.line(img_gray, tuple(hull[i][0]), tuple(hull[(i + 1) % length][0]), 255)
    cv.imshow('hull', img_gray)

    #填充凸包
    cv.fillPoly(img_gray, [hull], 255)
    cv.imshow('fill', img_gray)

    #多边形轮廓
    contours, _ = cv.findContours(img_gray, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    img_tmp = np.zeros((500, 600), dtype=np.uint8)
    cv.drawContours(img_tmp, contours, -1, 255, 1)
    cv.imshow('contours', img_tmp)
    cv.waitKey()

   

猜你喜欢

转载自blog.csdn.net/XLcaoyi/article/details/119853709