如何使用 OpenCV Python 對影像應用透視變換?
在透視變換中,即使在變換後,直線仍然保持直線。要應用透視變換,我們需要一個 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** 和 **pts2**。**pts1** 是輸入影像上四個點的陣列,**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()
輸出
執行後,它將生成以下輸出視窗:
左圖是輸入影像,右圖是透視變換後的輸出影像。