圖像透視變換¶
概要¶
講解OpenCV中投影的概念,還給出了一個投影的樣例.
keywords 投影 perspective-projection 圖像變形
什么是透視變換¶
之前我們在 仿射變換簡介 里面講解的是仿射變換AffineTransform。
那么透視變換與仿射變換之間最大的區別是什么呢?
畫面中兩個平行的邊,仿射變換過后,依然保持平行。 三點可以確定一個變換。
而透視變換則不一定,所以可以將仿射變換作為投影變換的一個特例。 需要四個點,才能確定透視變換。
舉一個來自官網的例子
Geometric Transformations of Images
import cv2 import matplotlib.pyplot as plt import numpy as np img = cv2.imread('sudokusmall.png') rows,cols,ch = 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,(300,300)) plt.subplot(121),plt.imshow(img),plt.title('Input') plt.subplot(122),plt.imshow(dst),plt.title('Output') plt.show()
透視變換的應用¶
下面這張圖片是原始圖像,我們相獲取A4紙上面的內容,而且我們也只關心這部分。
假設已經知道了A4紙四邊形的近似頂點在圖形中的坐標,如下所示:
[[[ 922 632]] [[ 659 2694]] [[3794 2630]] [[3362 857]]]
同時,因為之前邊緣處進行了膨脹,所以變換回去的時候, 可以內縮。
# 因為之前膨脹了很多次,所以四邊形區域需要向內收縮而且本身就有白色邊緣 margin=40 pts1 = np.float32([[921+margin, 632+margin], [659+margin, 2695-margin], [3795-margin, 2630-margin], [3362-margin, 856+margin]])
A4紙的寬高比在 1.4 : 1, 所以定義新圖片的四個頂點。
pts2 = np.float32([[0,0], [0, 1000], [1400, 1000], [1400, 0]])
M = cv2.getPerspectiveTransform(pts1,pts2) dst = cv2.warpPerspective(gray,M,(1400,1000))
最終得到了我們想要的圖片。
更詳細的流程見手寫數字識別專題中的:
尋找A4紙所在的四邊形區域與變形_paper-image-perspective-transformation