opencv

OpenCV怎么实现图像的几何变换如旋转和平移

小亿
84
2024-05-22 16:04:15
栏目: 编程语言

在OpenCV中,可以使用cv2.warpAffine()函数来实现图像的几何变换,包括旋转和平移。下面是一个简单的示例代码,演示如何使用OpenCV来实现图像的旋转和平移:

import cv2
import numpy as np

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

# 获取图像的高度和宽度
height, width = image.shape[:2]

# 定义旋转角度
angle = 45

# 定义平移距离
tx = width/4
ty = height/4

# 旋转矩阵
rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), angle, 1)

# 平移矩阵
translation_matrix = np.float32([[1, 0, tx], [0, 1, ty]])

# 执行旋转
rotated_image = cv2.warpAffine(image, rotation_matrix, (width, height))

# 执行平移
translated_image = cv2.warpAffine(rotated_image, translation_matrix, (width, height))

# 显示原始图像和处理后的图像
cv2.imshow('Original Image', image)
cv2.imshow('Transformed Image', translated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

在这个示例中,我们首先读取了一张图像,然后定义了旋转角度和平移距离。接着我们使用cv2.getRotationMatrix2D()函数来创建旋转矩阵,然后使用cv2.warpAffine()函数来执行图像的旋转。接着我们创建平移矩阵,并再次使用cv2.warpAffine()函数来执行图像的平移。最后我们显示原始图像和处理后的图像。

0
看了该问题的人还看了