python实现图片任意角度旋转并将旋转过后图片反射填充的代码
时间: 2023-11-09 19:04:39 浏览: 50
以下是Python实现图片任意角度旋转并将旋转过后图片反射填充的代码:
```python
import cv2
import numpy as np
def rotate_image(image, angle):
"""
旋转图片并将旋转后的部分进行反射填充
:param image: 原始图片
:param angle: 旋转角度
:return: 旋转后的图片
"""
# 获取图片宽高
height, width = image.shape[:2]
# 计算旋转后的图片宽高
new_width = int(height * np.abs(np.sin(np.radians(angle))) + width * np.abs(np.cos(np.radians(angle))))
new_height = int(width * np.abs(np.sin(np.radians(angle))) + height * np.abs(np.cos(np.radians(angle))))
# 创建旋转矩阵
rotation_matrix = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1)
# 计算平移距离
tx = (new_width - width) / 2
ty = (new_height - height) / 2
# 将旋转矩阵的平移部分进行调整
rotation_matrix[0, 2] += tx
rotation_matrix[1, 2] += ty
# 进行旋转
rotated_image = cv2.warpAffine(image, rotation_matrix, (new_width, new_height), flags=cv2.INTER_LINEAR,
borderMode=cv2.BORDER_REFLECT)
return rotated_image
```
使用方法:
```python
# 读取图片
image = cv2.imread("test.jpg")
# 旋转图片并反射填充
rotated_image = rotate_image(image, 45)
# 显示旋转后的图片
cv2.imshow("Rotated Image", rotated_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
其中,`rotate_image`函数接受两个参数:原始图片和旋转角度。旋转角度可以为正或负,表示顺时针或逆时针旋转。函数返回旋转后的图片。最后使用`cv2.imshow`函数显示旋转后的图片即可。