我编写了一个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问题:
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)