下面是一段代码的一部分,可通过简单的一行翻转图像:
for i in range(num_images):
im = cv2.imread(roidb[i]['image'])
if roidb[i]['hflipped']:
im = im[:, ::-1, :]
if roidb[i]['vflipped']:
im = im[::-1, :, :]
该hflipped
装置水平翻转图像,而vflipped
垂直翻转图像。我想添加另一部分以将每个图像逆时针旋转90度。
我尝试了2个选项,但它们都不起作用:
1)
if roidb[i]['rotated']:
im = im.rotate(im, 90)
2)
num_rows, num_cols = im.shape[:2]
if roidb[i]['rotated']:
rotation_matrix = cv2.getRotationMatrix2D((num_cols/2, num_rows/2), 90, 1)
img_rotation = cv2.warpAffine(im, rotation_matrix, (num_cols, num_rows))
有没有办法像翻转一样旋转图像?还是有更好的方法?
谢谢
由于OpenCV的Python包装器numpy
用作后端,因此请考虑使用numpy.rot90
专门用于将矩阵旋转90度的倍数的方法。这也适用于彩色图像,其中水平和垂直尺寸每个通道独立旋转。第二个参数是倍数k
,它指定要旋转图像的90度的倍数。正值执行逆时针旋转,而负值执行顺时针旋转。在您的情况下,将第二个参数指定为k=1
逆时针旋转90度。巧合的是,第二个参数的默认值为k=1
,因此您可以忽略它。如果您想顺时针旋转,则可以指定k=-1
。
将此逻辑添加到您的代码中如下:
import numpy as np
# Your setup code goes here...
# ...
# ...
# Main code in question
for i in range(num_images):
im = cv2.imread(roidb[i]['image'])
if roidb[i]['hflipped']:
im = im[:, ::-1, :]
if roidb[i]['vflipped']:
im = im[::-1, :, :]
if roidb[i]['rotated']: # New
im = np.rot90(im, k=1) # Rotates 90 degrees anti-clockwise
#im = np.rot90(im) # Also rotates 90 degrees anti-clockwise
#im = np.rot90(im, k=-1) # Rotates 90 degrees clockwise
# ...
# The rest of your code follows
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句