# 3.3. 图像的几何变换¶

## 3.3.1. 目标¶

• 学习将不同的几何变换应用于图像，如平移、旋转、仿射变换等。

• 您将看到这些功能： cv2.getPerspectiveTransform

## 3.3.2. 变换¶

OpenCV提供了两个转换函数， cv2.warpAffinecv2.warpPerspective ，可以进行各种转换。 cv2.warpAffine 获取2x3转换矩阵，而 cv2.warpPerspective 以3x3变换矩阵作为输入。

### 缩放比例¶

>>> import cv2
>>> import numpy as np
>>>
>>>
>>> res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)
>>>
>>> #OR
>>>
>>> height, width = img.shape[:2]
>>> res = cv2.resize(img,(2*width, 2*height), interpolation = cv2.INTER_CUBIC)


### 翻译¶

开始{aligned}M=begin{bmatrix}1&0&t戥x\0&1&t戥yend{bmatrix}end{aligned}

>>> import cv2
>>> import numpy as np
>>>
>>> rows,cols = img.shape
>>>
>>> M = np.float32([[1,0,100],[0,1,50]])
>>> dst = cv2.warpAffine(img,M,(cols,rows))
>>>
>>> # cv2.imshow('img',dst)
>>> # cv2.waitKey(0)
>>> # cv2.destroyAllWindows()

>>> %matplotlib inline
>>> import matplotlib.pyplot as plt
>>> plt.imshow(dst)

<matplotlib.image.AxesImage at 0x7ff412133828>


cv2.warpAffine() 函数第三个参数是输出图像的大小，它应该是 （宽度，高度） . 记住width=列数，height=行数。

### 旋转¶

开始{aligned}M=begin{bmatrix}costheta&-sintheta\sintheta&costhetaend{bmatrix}end{aligned}

开始{aligned}begin{bmatrix}alpha&beta&（1-alpha）cdot center.x-betacdot center.y-beta&alpha&betacdot center.x+（1-alpha）cdot center.yend{bmatrix}end{aligned}

开始{aligned}begin{array}{l}alpha=scalecdotcostheta，\beta=scalecdotsinthetaend{array}end{aligned}

>>> # img = cv2.imread('messi5.jpg',0)
>>> rows,cols = img.shape
>>>
>>> M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
>>> dst = cv2.warpAffine(img,M,(cols,rows))
>>>
>>> plt.imshow(dst)

<matplotlib.image.AxesImage at 0x7ff4108574e0>


### 仿射变换¶

>>> # img = cv2.imread('/cvdata/drawing.png')
>>> import cv2
>>>
>>>
>>> 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()


### 透视变换¶

>>> img = cv2.imread('/cvdata/sudoku.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()


## 3.3.3. 额外资源¶

1. “计算机视觉：算法和应用”，Richard Szeliski