目录
图像的裁剪、放大和缩小
错切变换
镜像变换
旋转变换
透视变换
import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
def show(img):
if img.ndim == 2:
plt.imshow(img, cmap='gray')
else:
plt.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))
plt.show()
img = cv.imread('pic/rabbit500x333.jpg')
show(img)
M = np.array([
[1, 0, 100],
[0, 1, 50]
], dtype=np.float32)
img2 = cv.warpAffine(img, M, (533, 560))
show(img2)
img = cv.imread('pic/rabbit500x333.jpg')
show(img)
M1 = np.array([
[1, 0.2, 0],
[0, 1, 0]
], dtype=np.float32)
M2 = np.array([
[1, 0, 0],
[0.3, 1, 0]
], dtype=np.float32)
img3 = cv.warpAffine(img, M1, (333,700))
img4 = cv.warpAffine(img, M2, (333,700))
show(img3)
show(img4)
Mx = np.array([
[-1, 0, 333],
[0, 1, 0]
], dtype=np.float32)
img2 = cv.warpAffine(img, Mx, (333, 500))
show(img2)
My = np.array([
[1, 0, 0],
[0, -1, 500]
], dtype=np.float32)
img3 = cv.warpAffine(img, My, (333, 500))
show(img3)
img4 = cv.flip(img, 1)#垂直
img5 = cv.flip(img, 0)#水平
img6 = cv.flip(img, -1)#同时
show(np.hstack([img, img4, img5, img6]))
h, w, c = img.shape
M2 = cv.getRotationMatrix2D((w//2, h//2), 45, 1)#center, angle, scale
img3 = cv.warpAffine(img, M2, (533, 500))
show(img3)
img = cv.imread('pic/parthenon500x750.jpg')
show(img)
src = np.array([
[210, 50],
[610, 270],
[650, 470],
[150, 450]
], dtype=np.float32)
dst = np.array([
[150, 50],
[650, 50],
[650, 470],
[150, 470]
], dtype=np.float32)
M = cv.getPerspectiveTransform(src, dst)
h, w, c = img.shape
img2 = cv.warpPerspective(img, M, (w, h))
show(img2)