2024-09-24 06:23:50 发布
网友
我生成一个随机噪声的图像,如下所示。在
image_shape = (299, 299, 3) image = np.random.uniform(size=image_shape) + 128.0
我需要旋转这个图像小幅度(-25到+25度)。我目前使用的是scipy.ndimage.rotate,但这会导致图像大部分变白。使用旋转ndarraynp.rot90型工作很好,但我不能像这样旋转图像,因为我只需要使用小角度。在
上面的代码生成以下输出:
我将创建一个函数,将输入图像中的每个像素映射到相应的旋转图像。 确保相对于中心像素旋转(如果这确实是您要查找的旋转)
(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]
我使用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))
如果一切顺利,请告诉我!在
PS:如果您对处理Python代码中的图像感兴趣,我强烈建议您关注adrianrosebrock的博客。在
我将创建一个函数,将输入图像中的每个像素映射到相应的旋转图像。 确保相对于中心像素旋转(如果这确实是您要查找的旋转)
我使用opencv来执行此操作,下面的代码假设您希望围绕其中心顺时针旋转:
如果一切顺利,请告诉我!在
PS:如果您对处理Python代码中的图像感兴趣,我强烈建议您关注adrianrosebrock的博客。在
相关问题 更多 >
编程相关推荐