如何确定透视变换后点在新图像平面中的位置?

3 python opencv transform image-processing perspectivecamera

我正在使用 OpenCV+Python+Numpy 并且我在图像中有三个点,我知道这些点的确切位置。

(P1, P2);
 N1
Run Code Online (Sandbox Code Playgroud)

我要将图像转换为另一个视图(例如,我将透视图转换为侧视图)。如果我这样做,我将无法获得图像平面中这三个点的确切位置。我应该以一种可以获得这些点的新坐标的方式编写代码。

   pts1=np.float32([[867,652],[1020,580],[1206,666],[1057,757]]) 

   pts2=np.float32([[700,732],[869,754],[906,916],[712,906]])


   matrix=cv2.getPerspectiveTransform(pts1,pts2)


   result=cv2.warpPerspective(Image1,matrix,(1920,1080))

   cv2.imshow('Image',Image1) cv2.imshow('Tran',result)
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何确定这 3 个点的新位置?

Leo*_*iga 10

很简单,您可以查看文档是如何warpPerspective工作的。要变换点的位置,您可以使用以下变换:

在此处输入图片说明

[x, y]原点在哪里,M是你的透视矩阵

在 python 中实现这一点,您可以使用以下代码:

p = (50,100) # your original point
px = (matrix[0][0]*p[0] + matrix[0][1]*p[1] + matrix[0][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))
py = (matrix[1][0]*p[0] + matrix[1][1]*p[1] + matrix[1][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))
p_after = (int(px), int(py)) # after transformation
Run Code Online (Sandbox Code Playgroud)

您可以在下面的代码中看到结果。红点是你的原点。第二个图显示了透视变换后它的去向。蓝色圆圈是您在上面的公式中计算的点。

蓝色

您可以在此处此处查看我的 Jupyter Notebook 。

编码:

import numpy as np
import cv2
import matplotlib.pyplot as plt

# load the image, clone it for output, and then convert it to grayscale
image = cv2.imread('sample.png')
pts1=np.float32([[867,652],[1020,580],[1206,666],[1057,757]]) 
pts2=np.float32([[700,732],[869,754],[906,916],[712,906]])
matrix=cv2.getPerspectiveTransform(pts1,pts2)

# Draw the point
p = (50,100)
cv2.circle(image,p, 20, (255,0,0), -1)

# Put in perspective
result=cv2.warpPerspective(image,matrix,(1500,800))

# Show images
plt.imshow(image)
plt.title('Original')
plt.show()

plt.imshow(result)
plt.title('Distorced')
plt.show()

# Here you can transform your point
p = (50,100)
px = (matrix[0][0]*p[0] + matrix[0][1]*p[1] + matrix[0][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))
py = (matrix[1][0]*p[0] + matrix[1][1]*p[1] + matrix[1][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))
p_after = (int(px), int(py))

# Draw the new point
cv2.circle(result,p_after, 20, (0,0,255), 12)

# Show the result
plt.imshow(result)
plt.title('Predicted position of your point in blue')
plt.show()
Run Code Online (Sandbox Code Playgroud)