16 仿射
16.1 平移
# 仿射变换之平移
import cv2
import numpy as np
# 导入图片
dog = cv2.imread('./image/dog.png')
h, w, ch = dog.shape
M = np.float32([[1, 0, 100], [0, 1, 0]])
# 注意opencv中是先宽度,再高度
new = cv2.warpAffine(dog, M, (w, h))
cv2.imshow('new', new)
cv2.waitKey(0)
cv2.destroyAllWindows()
16.2 旋转
仿射变换的难点就是计算变换矩阵, OpenCV提供了计算变换矩阵的API
getRotationMatrix2D(center, angle, scale)
- center 中心点,以图片的哪个点作为旋转时的中心点.
- angle角度:旋转的角度,按照逆时针旋转.
- scale缩放比例:想把图片进行什么样的缩放.
# 仿射变换之平移
import cv2
import numpy as np
# 导入图片
dog = cv2.imread('./image/dog.png')
h, w, ch = dog.shape
# M = np.float32([[1,0,100],[0,1,0]])
# 注意旋转的角度为逆时针.
M = cv2.getRotationMatrix2D((100, 100), 15, 1.0)
# 以图像中心点旋转
# M = cv2.getRotationMatrix2D((w / 2, h / 2), 15, 1.0)
# 注意.opencv中是先宽度,再高度
new = cv2.warpAffine(dog, M, (w, h))
cv2.imshow(' new', new)
cv2.waitKey(0)
cv2.destroyAllWindows()
16.3 透视变换
- warpPerspective(img, M, dsize,.…)
- 对于透视变换来说,M是一个3*3的矩阵.
- getPerspectiveTransfrm(src, dst)获取透视变换的变换矩阵,需要4个点,即图片的4个角
```python透视变换
import cv2
import numpy as np
导入图片
img = cv2.imread('./image/cat.png')
print(img.shape)
src = np.float32([[50, 50], [450, 50], [450, 50], [450, 450]])
dst = np.float32([[0, 0], [400, 0], [0, 400], [400, 400]])
M = cv2.getPerspectiveTransform(src, dst)
new = cv2.warpPerspective(img, M, (400, 400))
cv2.namedWindow('img', cv2.WINDOW_NORMAL)
cv2.resizeWindow('img', 640, 480)
cv2.namedWindow('new', cv2.WINDOW_NORMAL)
cv2.resizeWindow('new', 640, 480)
cv2.imshow('img ', img)
cv2.imshow('new', new)
cv2.waitKey(0)
cv2.destroyAllWindows()
```