扩展缩放
使用cv2.resize()来实现
缩放因子:
· 缩放 cv2.INTER_AREA
· 扩展 cv2.INTER_LINERA、cv2.INTER_CUBIC
# 下面的None本该是输出图片的尺寸,但这里因为后面我们设置了缩放因子
res1 = cv2.resize(img, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC)
res2 = cv2.resize(img, (2 * width, 2 * height), interpolation = cv2.INTER_CUBIC)
平移
构建矩阵M([1, 0, tx], [0, 1, ty]),类型为float32
tx,ty为要移动的距离
import numpy as np
import cv2
img = cv2.imread('a.JPEG')
cows, rols, channels = img.shape
# 构造矩阵
M = np.float32([[1, 0, 100], [0, 1, 50]])
# 第三个参数为输出图片的大小
dst = cv2.warpAffine(img, M, (cows, rols))
cv2.imshow('dst', dst)
cv2.imshow('img', img)
cv2.waitKey(0)
旋转
旋转与平移类似
使用cv2.getRotationMatrix2D()函数构造矩阵
import numpy as np
import cv2
img = cv2.imread('a.JPEG')
rows, cols, channels = img.shape
M = cv2.getRotationMatrix2D((rows/2, cols/2), 45, 0.6)
dst = cv2.warpAffine(img, M, (rows , cols ))
cv2.imshow(' dst', dst)
cv2.waitKey(0)
仿射变换
使用getAffineTransform函数构造矩阵
import numpy as np
import cv2
img = cv2.imread('a.JPEG')
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))
cv2.imshow('dst', dst)
cv2.waitKey(0)
透视变换
import numpy as np
import cv2
img = cv2.imread('a.JPEG')
rows, cols, ch = img.shape
pts1 = np.float32([[120, 65], [368, 52], [28, 387], [389, 390]])
pts2 = np.float32([[0, 0], [800, 0], [0, 800], [800, 800]])
# 构造矩阵,这里函数用的和上面的不同
M = cv2.getPerspectiveTransform(pts1, pts2)
# 变换使用的函数与上面也不同
dst = cv2.warpPerspective(img, M, (800, 800))
cv2.imshow('dst', dst)
cv2.waitKey(0)