轉 opencv 仿射變換相關

原文地址:https://segmentfault.com/a/1190000015645951

 

1圖像轉換

OpenCV提供了兩個轉換函數cv2.warpAffinecv2.warpPerspective,可以使用它們進行各種轉換。 cv2.warpAffine採用2x3變換矩陣,而cv2.warpPerspective採用3x3變換矩陣作爲輸入。

2圖像縮放

縮放只是調整圖像大小.爲此,OpenCV附帶了一個函數cv.resize().
cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])

  • 對shrinking,優選的interpolation方法:cv2.INTER_AREA該方法可以避免波紋的出現
  • 對zooming,優選的interpolation方法:cv2.INTER_CUBICcv2.INTER_LINEAR(默認)

方法一

import numpy as np
import cv2

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

res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)

方法二

import numpy as np
import cv2

height, width = img.shape[:2]
res = cv2.resize(img,(2*width, 2*height), interpolation = cv2.INTER_CUBIC)

3圖像平移


代碼

import cv2
import numpy as np

img = cv2.imread('img.jpg',0)
rows,cols = img.shape

M = np.float32([[1,0,100],[0,1,50]])
dst = cv2.warpAffine(img,M,(cols,rows))

cv2.imshow('img',img)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

4圖像旋轉

通過變換矩陣實現圖像旋轉角度θ:

爲了找到這個轉換矩陣,OpenCV提供了一個函數cv2.getRotationMatrix2D.

應用

將圖像相對於中心旋轉90度而不進行任何縮放
代碼

import cv2
import numpy as np

img = cv2.imread('img.jpg',0)
rows,cols = img.shape

# cols-1 and rows-1 are the coordinate limits.
M = cv2.getRotationMatrix2D(((cols-1)/2.0,(rows-1)/2.0),90,1)
dst = cv2.warpAffine(img,M,(cols,rows))


cv2.imshow('img',img)
cv2.imshow('dst',dst)
cv2.waitKey(0)
cv2.destroyAllWindows()

 

5仿射變換

在仿射變換中,原始圖像中的所有平行線仍將在輸出圖像中平行。 爲了找到變換矩陣,我們需要輸入圖像中的三個點及其在輸出圖像中的相應位置。 然後cv.getAffineTransform將創建一個2x3矩陣,該矩陣將傳遞給cv.warpAffine。
代碼

import cv2
import numpy as np
import matplotlib.pylab  as plt

img = cv2.imread('img5.jpg')
rows,cols,ch = img.shape

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

M = cv2.getAffineTransform(pts1,pts2)

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

plt.subplot(121),plt.imshow(img),plt.title('Input')
plt.subplot(122),plt.imshow(dst),plt.title('Output')
plt.show()

 

5透視變換

對於透視變換,需要一個3x3變換矩陣。 即使在轉換之後,直線仍將保持筆直. 要找到此變換矩陣,輸入圖像上需要4個點,輸出圖像上需要相應的點. 在這4個點中,其中3個不應該共線. 然後可以通過函數cv2.getPerspectiveTransform找到變換矩陣. 然後將cv2.warpPerspective應用於此3x3變換矩陣。

代碼

import cv2
import numpy as np
import matplotlib.pylab  as plt

img = cv2.imread('img6.jpg')
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()

 

NOTE
仿射變換和透視變換更直觀的叫法可以叫做“平面變換”和“空間變換”或者“二維座標變換”和“三維座標變換”.
從另一個角度也能說明三維變換和二維變換的意思,仿射變換的方程組有6個未知數,所以要求解就需要找到3組映射點,三個點剛好確定一個平面.透視變換的方程組有8個未知數,所以要求解就需要找到4組映射點,四個點就剛好確定了一個三維空間.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章