如何使用 OpenCV Python 对图像应用透视变换?

opencvpythonserver side programmingprogramming

在透视变换中,直线即使在变换后仍保持笔直。要应用透视变换,我们需要一个 3×3 透视变换矩阵。我们需要输入图像上的四个点和输出图像上的相应四个点。

我们应用 cv2.getPerspectiveTransform() 方法来查找变换矩阵。其语法如下 −

M = cv2.getPerspectiveTransform(pts1,pts2)

其中,

  • pts1 − 输入图像上的四个点的数组,

  • pts2 − 输出图像上对应的四个点的数组。

透视变换矩阵 M 是一个 numpy 数组。我们将 M 作为参数传递给 cv2.warpAffine() 函数来计算透视变换。它的语法是 −

cv2.warpAffine(img,M,(cols,rows))

其中,

  • img − 要转换的图像。

  • M − 上面定义的透视变换矩阵。

  • (cols, rows) − 转换后图像的宽度和高度。

要对图像应用透视变换,您可以按照以下步骤进行操作 −

步骤

导入所需的库。在以下所有 Python 示例中,所需的 Python 库都是 OpenCV。确保您已经安装了它。

import cv2

使用 cv2.imread() 函数读取输入图像。传递输入图像的完整路径。

img = cv2.imread('warning_wall.jpg')

定义 pts1 pts2pts1 是输入图像上的四个点的数组,pts2 是输出图像上对应的四个点的数组。

pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
pts2 = np.float32([[100,50],[300,0],[0,300],[300,300]])

使用 cv2.getPerspectiveTransform(pts1, pts2) 函数计算透视变换矩阵 M。

M = cv2.getPerspectiveTransform(pts1,pts2)

变换图像使用 cv2.warpAffine() 方法传递透视变换矩阵作为参数。 cols 和 rows 是转换后图像所需的宽度和高度。

dst = cv2.warpAffine(img,M,(cols,rows))

显示转换后的图像。

cv2.imshow("Transformed Image", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

让我们看一些例子,以便更好地理解它是如何完成的。

我们将使用此图像作为以下示例的输入文件

示例1

在此示例中,我们对输入图像执行透视变换。我们将输出图像的宽度和高度设置为与输入图像相同。

# import required libraries import cv2 import numpy as np # read the input image img = cv2.imread('warning_wall.jpg') # find the height and width of image # width = number of columns, height = number of rows in image array rows,cols,ch = img.shape # define four points on input image pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]]) # define the corresponding four points on output image pts2 = np.float32([[100,50],[300,0],[0,300],[300,300]]) # get the perspective transform matrix M = cv2.getPerspectiveTransform(pts1,pts2) # transform the image using perspective transform matrix dst = cv2.warpPerspective(img,M,(cols, rows)) # display the transformed image cv2.imshow('Transformed Image', dst) cv2.waitKey(0) cv2.destroyAllWindows()

输出

执行时,此 Python 程序将生成以下输出窗口 -

上述输出图像是在输入图像上进行透视变换后获得的。

示例 2

在此示例中,我们对输入图像执行透视变换。我们将输出图像的宽度和高度设置为 (600, 350)。它与输入图像的宽度和高度不同。

import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('warning_wall.jpg',0) rows,cols = img.shape pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]]) pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]]) M = cv2.getPerspectiveTransform(pts1,pts2) dst = cv2.warpPerspective(img,M,(600,350)) plt.subplot(121),plt.imshow(img, cmap='gray'),plt.title('Input') plt.subplot(122),plt.imshow(dst, cmap='gray'),plt.title('Output') plt.show()

输出

执行后,将生成以下输出窗口 -

左图为输入图像,右图为透视变换后的输出图像。


相关文章