温馨提示×

如何用Python实现图像的仿射变换与透视变换

小亿
87
2024-04-29 19:02:53
栏目: 编程语言

要实现图像的仿射变换和透视变换,可以使用Python中的OpenCV和NumPy库。下面是使用这两个库实现图像的仿射变换和透视变换的示例代码:

  1. 仿射变换:
import cv2
import numpy as np

# 读取图像
img = cv2.imread('image.jpg')

# 定义仿射变换矩阵,例如将图像向右平移100像素,向下平移50像素
M = np.float32([[1, 0, 100], [0, 1, 50]])

# 应用仿射变换
rows, cols = img.shape[:2]
img_affine = cv2.warpAffine(img, M, (cols, rows))

# 显示处理后的图像
cv2.imshow('Affine Transformation', img_affine)
cv2.waitKey(0)
cv2.destroyAllWindows()
  1. 透视变换:
import cv2
import numpy as np

# 读取图像
img = cv2.imread('image.jpg')

# 定义透视变换矩阵,例如将图像的四个角点分别映射到新的位置
pts1 = np.float32([[50, 50], [200, 50], [50, 200], [200, 200]])
pts2 = np.float32([[10, 100], [200, 50], [100, 250], [280, 200]])
M = cv2.getPerspectiveTransform(pts1, pts2)

# 应用透视变换
img_perspective = cv2.warpPerspective(img, M, (cols, rows))

# 显示处理后的图像
cv2.imshow('Perspective Transformation', img_perspective)
cv2.waitKey(0)
cv2.destroyAllWindows()

以上示例代码分别实现了图像的仿射变换和透视变换,可以根据具体需求调整变换矩阵和变换的参数。

0