【问题标题】:rotate an image without using OpenCV in python 3在 python 3 中不使用 OpenCV 旋转图像
【发布时间】:2023-03-28 08:45:01
【问题描述】:

我正在尝试在不使用 OpenCv 库的情况下使用最近邻和双线性插值在 python 中旋转图像,这是我的方法:

import matplotlib.image as img
import numpy as npy
import math

m = img.imread("room.png");

w, h = m.shape[:2];

newImage = npy.zeros([w,h, 4]);

for i in range(w - 1):
    for j in range(h - 1):
        newImage[i , j] = m[int(math.cos(30)*(i-w/2)+math.sin(30)*(j-h/2) + w/2),int(math.cos(30)*(j-h/2)-math.sin(30)*(i-w/2) + h/2)]

img.imsave('rotated.png', newImage);

但我找不到为什么它不能正常工作,这是我得到的错误:

IndexError: 索引 852 超出轴 1 的范围,大小为 852

【问题讨论】:

  • 旋转坐标时,一些像素最终会超出原始图像。您需要测试您的计算坐标,如果它们在输入图像之外,则填写 0。
  • 请记住 math.sin 和 math.cos 采用弧度角...我建议用 npy.pi/6 替换您的 30 ...但这不是问题的根源。当您以相同的比例旋转方形图像时,输出图像会更大或者您需要对其进行裁剪。
  • @ma3oun 是的,我改了,谢谢提醒

标签: python image-processing


【解决方案1】:

如果像素的坐标在原始图像之外结束,我应该已经确定了:

for i in range(w - 1):
    for j in range(h - 1):
        pixelNewX = int(math.cos(math.pi/6)*(i-w/2)+math.sin(math.pi/6)*(j-h/2)+w/2)
        pixelNewY = int(math.cos(math.pi/6)*(j-h/2)-math.sin(math.pi/6)*(i-w/2)+h/2)
        if 0 <= pixelNewX < w and 0 <= pixelNewY < h :
            newImage[i, j] = m[pixelNewX, pixelNewY]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 2015-02-03
    相关资源
    最近更新 更多