python - 在不使用包和使用变换矩阵的情况下在 Python 中旋转彩色图像
问题描述
我正在尝试创建一种将 Python 中的彩色图像旋转 0、90、180 或 270 度的方法。到目前为止,这是我的代码。就目前而言,输出是空白图像。我也试图让代码尽可能高效。不知道我做错了什么。Image 是一个 3D 数组,而 rotate_angle 是一个 int。我尝试的想法是从原始图像中获取像素的所有 (x,y) 坐标,并将它们与变换矩阵 (x_transformed, y_transformed) 相乘。然后,新图像上 (x_transformed, y_transformed) 处的颜色将只是旧图像上 (x,y) 处的颜色。
def rotate_image(image, rotate_angle):
output_image = image
# Convert degrees to radian
angle = math.radians(rotate_angle)
# For all values of height
for i in range(image.shape[0]):
# And all values of width
for j in range(image.shape[1]):
# Take the x and y coordinates of the existing points
y = image.shape[0]-1
x = image.shape[1]-1
# Keep in mind rotation matrix is [(cos, sin), (-sin, cos)] [(x,y)]
y_n = int(-x * math.sin(angle) + y * math.cos(angle))
x_n = int(x * math.cos(angle) + y * math.sin(angle))
# Rotating to where we are and then copying data from where we were
output_image[y_n, x_n, :] = image[i, j, :]
return output_image
当然,如果有更高效的方法,我也有兴趣知道它是什么。我知道那里有可以做我正在做的事情的包,但我希望自己和使用我拥有的工具来制作方法。
解决方案
推荐阅读
- arrays - 为什么在循环(有时为空)变体时出现(运行时错误'13':)类型不匹配?
- mongodb - Mongo DB sort by date and group by tag
- python - 尝试在 python 中运行 OpenALPR 时出错
- java - 在 Mock 对象上调用的方法的 Mockito NullPointer 异常
- java - 滚动窗格是否可以在 Java 中有多个选项卡?
- r - R从DF创建JSON列表
- c++ - 我的 A* 搜索算法在执行时进入了一个无限循环,我真的很困惑为什么。有人可以帮我吗?
- python - 请在路线规划器练习的代码中找到不可见的错误
- dart - 处理 AngularDart 组件中的 keydown 事件
- python - 选项卡上的 Jupyter 自动完成/建议不起作用