如何在 OpenCV Python 中對影像應用仿射變換?


在仿射變換中,原始影像中所有平行線在輸出影像中仍然平行。要對影像應用仿射變換,我們需要輸入影像上的三個點和輸出影像上對應的三個點。因此,首先,我們定義這些點並傳遞給函式cv2.getAffineTransform()。它將建立一個 2×3 矩陣,我們稱之為變換矩陣 M。

我們可以使用以下語法找到變換矩陣 M:

M = cv2.getAffineTransform(pts1,pts2)

其中pts1是輸入影像上三個點的陣列,pts2是輸出影像上對應三個點的陣列。變換矩陣M是型別為np.float64的 NumPy 陣列。

我們將M作為引數傳遞給cv2.warpAffine()函式。請參閱下面給出的語法

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

其中,

  • img - 要進行仿射變換的影像。

  • M - 上述定義的仿射變換矩陣。

  • (cols, rows) - 仿射變換後圖像的寬度和高度。

步驟

要執行影像仿射變換,您可以按照以下步驟操作:

匯入所需的庫。在以下所有 Python 示例中,所需的 Python 庫是OpenCV。確保您已安裝它。

import cv2

使用cv2.imread()函式讀取輸入影像。傳遞輸入影像的完整路徑。

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

定義pts1pts2。我們需要輸入影像中的三個點及其在輸出影像中的對應位置。

pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])

使用cv2.getAffineTransform(pts1, pts2)函式計算仿射變換矩陣M

M = cv2.getAffineTransform(pts1, pts2)

使用cv2.warpAffine()方法變換影像。cols 和 rows 是變換後圖像所需的寬度和高度。

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

顯示仿射變換後的影像。

cv2.imshow("Affine Transform", dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

讓我們看一些示例,以清楚地瞭解如何在影像上應用仿射變換

輸入影像

我們將在下面的示例中使用以下影像作為輸入檔案:

示例 1

在這個程式中,我們將看到如何對輸入影像執行仿射變換。

# import required libraries import cv2 import numpy as np # read the input image img = cv2.imread('lines.jpg') # access the image height and width rows,cols,_ = img.shape # define at three point on input image pts1 = np.float32([[50,50],[200,50],[50,200]]) # define three points corresponding location to output image pts2 = np.float32([[10,100],[200,50],[100,250]]) # get the affine transformation Matrix M = cv2.getAffineTransform(pts1,pts2) # apply affine transformation on the input image dst = cv2.warpAffine(img,M,(cols,rows)) cv2.imshow("Affine Transform", dst) cv2.waitKey(0) cv2.destroyAllWindows()

輸出

以上 Python 程式將生成以下輸出視窗:

示例 2

在這個 Python 程式中,我們載入一個灰度影像,定義對應於輸入和輸出影像的兩個點,獲取變換矩陣,最後應用warpAffine()方法對輸入影像執行仿射變換。

import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('lines.jpg', 0) rows,cols = img.shape pts1 = np.float32([[150,50],[200,50],[50,200]]) pts2 = np.float32([[10,100],[200,50],[10,250]]) M = cv2.getAffineTransform(pts1,pts2) dst = cv2.warpAffine(img,M,(cols,rows)) plt.subplot(121), plt.imshow(img, cmap='gray' ), plt.title('Input') plt.subplot(122), plt.imshow(dst, cmap='gray'), plt.title('Output') plt.show()

輸出

執行後,它將生成以下輸出視窗:

更新於: 2022年9月27日

4K+ 閱讀量

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告