如何在opencv中撤消单个点的透视变换

How to undo a perspective transform for a single point in opencv

本文关键字:单个点 透视变换 撤消 opencv      更新时间:2023-10-16

我正在尝试使用反向透视图进行一些图像分析。我使用openCV函数getTransform和findHomography生成一个变换矩阵,并将其应用于源图像。这很有效,我能够从我想要的图像中获得分数。问题是,我不知道如何获取单个点值并撤消变换,将它们绘制回原始图片上。我只想撤消这组点的变换,以找到它们的原始位置。如何做到这一点。这些点的形式为openCV库中的点(x,y)。

要反转单应性(例如透视变换),通常只需反转变换矩阵。

因此,要将一些点从目标图像转换回源图像,需要反转转换矩阵,并将这些点转换为结果。要用变换矩阵变换一个点,可以将其从右乘到矩阵,然后可能进行去均匀化。

幸运的是,OpenCV不仅提供了warpAffine/warpPerspective方法,将一张图像的每个像素转换为另一张图像,而且还提供了转换单个点的方法。

使用cv::perspectiveTransform(inputVector, emptyOutputVector, yourTransformation)方法变换一组点,其中

inputVectorstd::vector<cv::Point2f>(您也可以使用nx2或2xn矩阵,但有时这是错误的)。相反,您可以使用cv::Point3f类型,但我不确定这些是同源坐标点还是用于3D变换的3D点(或者两者都有?)。

outputVector是空的std::vector<cv::Point2f>,结果将存储在中

yourTransformation是双精度3x3cv::Mat(类似于findHomography提供的)变换矩阵(或3D点的4x4)。

下面是一个Python示例:

import cv2
import numpy as np
# Forward transform
point_transformed = cv2.perspectiveTransform(point_original, trans)
# Reverse transform
inv_trans = np.linalg.pinv(trans)
round_tripped = cv2.perspectiveTransform(point_transformed, inv_trans)
# Now, round_tripped should be approximately equal to point_original

您可以使用cv::perspectiveTransform(inputVector, emptyOutputVector, yourTransformation)对点应用透视变换

Python:cv2.perspectiveTransform(src, m) → dst

src–输入双通道或三通道浮点数组;每个元素是要变换的2D/3D矢量。m–cv2.getPerspectiveTransform(_src, _dst) 先前计算的3x3或4x4浮点变换矩阵

在python中,您必须在numpy数组中传递点,如下所示:

points_to_be_transformed = np.array([[[0, 0]]], dtype=np.float32)
transfromed_points = cv2.perspectiveTransform(points_to_be_transformed, m)

transfromed_points的形状也将与输入数组相同:points_to_be_transformed