# 图像的翻转
import cv2
import numpy as np
# 读取图片
doge = cv2.imread('./doge.jpg')
new_doge1 = cv2.flip(doge, flipCode=0)
new_doge2 = cv2.flip(doge, flipCode=1)
new_doge3 = cv2.flip(doge, flipCode=-1)
cv2.imshow('flip', np.hstack((doge, new_doge1, new_doge2, new_doge3)))
cv2.waitKey(0)
cv2.destroyAllWindows()
使用ndarray进行上下+左右翻转:
# 图像的翻转
import cv2
import numpy as np
doge = cv2.imread('./doge.jpg')
new_doge = dog[::-1, ::-1]
cv2.imshow('ndarray_flip', np.hstack((doge, new_doge)))
cv2.waitKey(0)
cv2.destroyAllWindows()
# 图像的旋转
import cv2
import numpy as np
# 读取图片
dog = cv2.imread('./dog.jpg')
new_dog1 = cv2.rotate(dog, rotateCode=cv2.ROTATE_90_CLOCKWISE)
new_dog2 = cv2.rotate(dog, rotateCode=cv2.ROTATE_180)
new_dog3 = cv2.rotate(dog, rotateCode=cv2.ROTATE_90_COUNTERCLOCKWISE)
cv2.imshow('flip', np.hstack((dog, new_dog1, new_dog2, new_dog3)))
cv2.waitKey(0)
cv2.destroyAllWindows()
在CSS3的transform属性中,matrix(n,n,n,n,n,n)值就使用了仿射变换来操作图像的旋转、缩放、平移。
# 仿射变换之平移
import cv2
import numpy as np
# 导入图片
dog = cv2.imread('./dog.jpg')
h, w, ch = dog.shape
# x轴正向偏移50,y轴正向偏移50
M = np.float32([[1, 0, 50], [0, 1, 50]])
# 注意OpenCV中先宽度后高度
new = cv2.warpAffine(dog, M, (w, h))
cv2.imshow('Affine', new)
cv2.waitKey(0)
cv2.destroyAllWindows()
仿射变换的难点就是计算变换矩阵,OpenCV提供了计算变换矩阵的API。
# 除了平移,仿射矩阵还可以完成图像的旋转
# 旋转同样需要进行矩阵计算,为了方便计算旋转矩阵
# 使用getRotationMatrix2D方法可以获得想要的旋转矩阵
import cv2
import numpy as np
# 导入图片
dog = cv2.imread('./dog.jpg')
h, w, ch = dog.shape
# 获取变换矩阵,逆时针45度转动并缩放至0.7倍
M = cv2.getRotationMatrix2D((w/2, h/2), 45, 0.7)
new = cv2.warpAffine(dog, M, (w, h))
cv2.imshow('Affine', np.hstack((dog, new)))
cv2.waitKey(0)
cv2.destroyAllWindows()
# 通过三点的起止位置来获得变换矩阵
import cv2
import numpy as np
dog = cv2.imread('./dog.jpg')
h, w, ch = dog.shape
# 顺时针旋转90度后的起止三个点的坐标
src = np.float32([[0,0], [100,0], [0,100]])
dst = np.float32([[100,0], [100,100], [0,0]])
# 需要原始图片的三点坐标,和变换之后三个对应的坐标
M = cv2.getAffineTransform(src, dst)
new = cv2.warpAffine(dog, M, (w, h))
cv2.imshow('Affine', np.hstack((dog, new)))
cv2.waitKey(0)
cv2.destroyAllWindows()
透视变换就是将二位坐标系转变为三维坐标系。
# 通过三点的起止位置来获得变换矩阵
import cv2
import numpy as np
img = cv2.imread('./book.jpg')
print(img.shape)
# 获取变换矩阵
# src是原图中对象的最小外接矩形的4个顶点坐标
src = np.float32([[0, 540], [2000, 540], [2500, 1986], [0, 1986]])
dst = np.float32([[0, 0], [2000, 0], [2100, 1446], [0, 1446]])
M = cv2.getPerspectiveTransform(src, dst)
# 透视变换
new = cv2.warpPerspective(img, M, (1600, 1446))
cv2.imshow('Affine_raw', img)
cv2.imshow('Affine_new', new)
cv2.waitKey(0)
cv2.destroyAllWindows()