如何正确旋转ndarray(图像)?

时间:2018-01-27 19:23:38

标签: python python-3.x numpy matplotlib

我生成一个随机噪声图像,如下所示。

image_shape = (299, 299, 3)
image = np.random.uniform(size=image_shape) + 128.0

我需要少量旋转此图像(-25到+25度)。我目前正在使用scipy.ndimage.rotate,但这会导致图像变成白色。使用np.rot90旋转ndarray工作正常,但我不能像这样旋转图像,因为我只需要使用小角度。

plot_image(image)
plot_image(np.rot90(image))
plot_image(rotate(image, 5))

上面的代码产生以下输出:

enter image description here

3 个答案:

答案 0 :(得分:2)

在原始问题中的行:

image = np.random.uniform(size=image_shape) + 128.0

创建一个像素值都在 128 到 129 之间的图像。然后可视化自动缩放这些值之间的颜色图。旋转后,角点出现值为 0 的像素。自动缩放然后映射 0 到 129 之间的颜色比例,从而提供黑白方面。

答案 1 :(得分:-1)

我使用opencv执行此操作,以下代码假设您希望围绕其中心顺时针旋转它:

import numpy as np
import cv2

def rotate(img, angle):
    img = cv2.imread(img)
    (height, width) = img.shape[:2]
    (cent_x, cent_y) = (width // 2, height // 2)

    mat = cv2.getRotationMatrix2D((cent_x, cent_y), -angle, 1.0)
    cos = np.abs(mat[0, 0])
    sin = np.abs(mat[0, 1])

    n_width = int((height * sin) + (width * cos))
    n_height = int((height * cos) + (width * sin))

    mat[0, 2] += (n_width / 2) - cent_x
    mat[1, 2] += (n_height / 2) - cent_y

    return cv2.warpAffine(img, mat, (n_width, n_height))

Lemme知道一切运作良好!

PS:如果您对使用Python代码操纵图像感兴趣,我强烈建议您关注Adrian Rosebrock的博客。

答案 2 :(得分:-1)

我会创建一个函数,将输入图像中的每个像素映射到相应的旋转图像。 确保相对于中心像素旋转(如果这确实是您正在寻找的旋转)

(rows, cols) = img.shape
mid_coords = np.floor(0.5*np.array(img.shape))

def rotate_pixel(pixel_coords, cos_angle, sin_angle):
    x = mid_coords[0] + (pixel_coords[0] - mid_coords[0]) * cos_angle
    y = mid_coords[1] + (pixel_coords[1] - mid_coords[1]) * sin_angle
    if 0<=x<rows and 0<=y<cols:
       return (x,y)
    else:
       return False

rotated_img = np.zeros((rows, cols))
cos_angle = np.cos(angle)
sin_angle = np.sin(angle)
for i in range(rows):
   for k in range(cols):
       coords = rotate_pixel((i,k), cos_angle, sin_angle)
       if(coords):
           rotated_img[coords] = img[i][k]
相关问题