Hadi GhahremanNezhad Hadi GhahremanNezhad - 1 month ago 12
Python Question

Rotating images doesn't work

Below there is a part of a code which flips images by a simple line:

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, :, :]


The
hflipped
means flipping images horizontally and the
vflipped
means flipping them vertically. I want to add another part to rotate each image by 90 degrees anticlockwise.

I have tried 2 options, but neither of them works:

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))


Is there a way to rotate the images similar to the flipping? Or there is a better way?

Thanks

Answer Source

Because the Python wrappers to OpenCV use numpy as the backend, consider using numpy.rot90 which is specifically designed to rotate matrices by multiples of 90 degrees. This also works for colour images where the horizontal and vertical dimensions are rotated independently per channel. The second parameter is a multiple k which specifies how many multiples of 90 degrees you would like to rotate the image. Positive values perform anti-clockwise rotation while negative values perform clockwise rotation. In your case, specify the second parameter as k=1 to rotate 90 degrees anti-clockwise. Coincidentally, the default value for the second parameter is k=1, so you can omit it. If you wanted to rotate clockwise though, you would specify k=-1.

Adding this logic to your code would be as follows:

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