# 几何变换
import cv2
import numpy as np
from matplotlib import pyplot as plt
def show(img):
print("The current input image shape is", img.shape)
cv2.imshow("images", img)
cv2.waitKey()
cv2.destroyAllWindows()
# BGR 2 RGB
img = cv2.imread("girl.jpg", 1)[...,::-1]
h, w, c = img.shape
print(h, w, c)
# 平移
# 平移变换矩阵 形式--->[[1, 0, tx], [0, 1, ty]]
# 数据转为np.float32类型
M = np.float32([[1,0,100],[0,1,50]])
dst = cv2.warpAffine(img, M, (w,h)) # 平移矩阵 (源图, 变换矩阵, 输出图像大小)
# show(dst)
# 旋转变换
# getRotationMatrix2D --> (旋转点,旋转角度, 缩放比例)
M = cv2.getRotationMatrix2D((w/3, h/3), 45, 0.4)
dst = cv2.warpAffine(img, M, (w, h))
# show(dst)
# 仿射变换
# 仿射变换是一种二维坐标到二维坐标之间的线性变换,并保持二维图形的“平直性”。转换前平行的线,在转换后依然平行
# 需要提供原图像中三个点以及他们在输出图像中的位置
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, (w, h))
# plt.subplot(121), plt.imshow(img), plt.title("Input")
# plt.subplot(122), plt.imshow(dst), plt.title("Output")
# plt.show()
# 透视变换
# 需要在原图上找到4个点,以及他们在输出图上对应的位置,这四个点中任意三个都不能共线
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,(w, h))
plt.subplot(121), plt.imshow(img), plt.title("Input")
plt.subplot(122), plt.imshow(dst), plt.title("Output")
plt.show()
Python_opencv几何变换
最新推荐文章于 2022-10-29 16:14:48 发布