function cv2.getPerspectiveTransform
从四对对应点计算透视变换的3x3矩阵.
我有一个具有透视失真的池表的image,在手动 Select 四个角(按左上角、右上角、左下角、右下角的顺序)时,cv2.getPerspectiveTransform
计算将池表的角转换为显示窗口的角所需的3x3矩阵.然后,我应用cv2.warpPerspective
将池表图像与计算出的矩阵不失真.
我想使用此矩阵将各个点从扭曲的池表图像转换为未扭曲的池表图像.当我试图通过将3x3变换矩阵乘以角点坐标(按照链接文档写为(x,y,1))来用变换矩阵变换扭曲池表的相同手动 Select 角点时,变换后的角点与所显示窗口的角点不匹配(如下所示).也就是说,红点应该在图像的角落,但不是.
有人能解释一下为什么变换后的角点与显示窗口的角点不匹配吗?
以下是我的代码:
import cv2
import numpy as np
def mouse_position(event, mouse_x, mouse_y, flags, param):
global corners
if event == cv2.EVENT_LBUTTONDOWN:
print(f"Corner #{len(corners) + 1}: {(mouse_x, mouse_y)}")
corners.append((mouse_x, mouse_y))
corners = []
img = cv2.imread("Assets/Setup.jpg")
cv2.namedWindow("Select Corners of Pool Table")
cv2.setMouseCallback("Select Corners of Pool Table", mouse_position)
while len(corners) < 4:
cv2.imshow("Select Corners of Pool Table", img)
if cv2.waitKey(1) != -1:
print("Exiting program.")
cv2.destroyAllWindows()
exit(0)
cv2.destroyAllWindows()
corners = np.array(corners, dtype="float32")
height, width = img.shape[:2]
transform_matrix = cv2.getPerspectiveTransform(corners, np.array([(0, 0), (width, 0), (0, height), (width, height)],
dtype="float32"))
undistorted_image = cv2.warpPerspective(img, transform_matrix, (width, height))
transformed_corners = (transform_matrix @ np.hstack((corners, np.ones((corners.shape[0], 1)))).T).T.astype(int)
for corner in transformed_corners:
cv2.circle(undistorted_image, (corner[0], corner[1]), 30, (0, 0, 255), -1)
cv2.imshow("Frame", undistorted_image)
cv2.waitKey(0)
cv2.destroyAllWindows()