如何使用 OpenCV 绘图函数绘制填充矩形?

How do I draw a filled rectangle using OpenCV's drawing functions?

我写了一个 Python 脚本,它基本上是逐帧解析视频,并使用特征匹配 + 单应性检测与给定图像的相似性,并在图像出现的区域周围绘制边界框视频。我是 OpenCV 的新手,因此我无法真正理解使用哪个函数来绘制填充矩形而不是边界框(我使用的是多段线)。

我猜我必须使用 'fillpoly' 或 'fillConvexPoly' 但我对使用哪些参数以及如何实现它感到困惑。到目前为止,这是我的代码。

    import cv2
    import numpy as np
    img = cv2.imread("template.png", cv2.IMREAD_GRAYSCALE) 
    cap = cv2.VideoCapture("video.mp4")

    fourcc = cv2.VideoWriter_fourcc(*'xvid')
    out = cv2.VideoWriter('output.avi',fourcc, 25.0, (1280,718))

    # Features
    sift = cv2.xfeatures2d.SIFT_create()
    kp_image, desc_image = sift.detectAndCompute(img, None)

    # Feature matching
    index_params = dict(algorithm=0, trees=5)
    search_params = dict()
    flann = cv2.FlannBasedMatcher(index_params, search_params)

    while True :
        _, frame = cap.read()
        grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        kp_grayframe, desc_grayframe = sift.detectAndCompute(grayframe, None)
        matches = flann.knnMatch(desc_image, desc_grayframe, k=2)

        good_points = []
        for m, n in matches:
            if m.distance < 0.6 * n.distance:
                good_points.append(m)

        if (len(good_points)>10):
            query_pts = np.float32([kp_image[m.queryIdx].pt for m in good_points]).reshape(-1, 1, 2)
            train_pts = np.float32([kp_grayframe[m.trainIdx].pt for m in good_points]).reshape(-1, 1, 2)
            matrix, mask = cv2.findHomography(query_pts, train_pts, cv2.RANSAC, 5.0)
            matches_mask = mask.ravel().tolist()

            # Perspective transform
            h, w = img.shape
            pts = np.float32([[0, 0], [0, h], [w, h], [w, 0]]).reshape(-1, 1, 2)
            dst = cv2.perspectiveTransform(pts, matrix)

            homography = cv2.polylines(frame, [np.int32(dst)], True, (0,255, 0), 3) #this is the line i want to change
            out.write(homography)
            cv2.imshow("Homography", homography)

        else:
            cv2.imshow("Homography", grayframe)


        cv2.imshow("grayFrame", grayframe)

        key = cv2.waitKey(1)
        if key & 0xFF == ord('q'):
            break

    cap.release()
    out.release()
    cv2.destroyAllWindows()

如你所言,你可以使用cv2.fillPoly()

您可能需要查看 cv2.fillPoly() 文档 here

或这些相关的 SO 问题:

  • What does the python interface to opencv2.fillPoly want as input?
import cv2
import numpy as np

image = np.zeros(shape=(512, 512, 3), dtype=np.uint8)
points = np.array([[225, 150], [103, 320], [350, 250], [222, 245]],
                  dtype=np.int32)

cv2.fillPoly(image, [points], (0, 255, 0))
cv2.imshow('polygon', image)
cv2.waitKey(0)