pythonimagerotationoverwritendimage

Why aren't my rotated images being saved properly?


I need to rotate around 150 images different amounts so that I can properly annotate my data with bounding boxes. The issue is that for some reason the image files aren't being saved rotated after running through my code and entering some values. How do I save these images in a rotated fashion so when I reopen the image file it's already rotated?

The file should be properly overwritten given I've gone as far as actually deleting the file entirely and saving a new one under the same name.

import os
from skimage import io, transform
import cv2
from scipy import ndimage
import scipy.misc

folder_name = r'C:\Users\admin\Desktop\Pedro_Database\Setup_Data\test'
with os.scandir(folder_name) as folder:
    for file in folder:
        if (file.name.endswith('.bmp')):
            path = folder_name + '/' + file.name
            img = cv2.imread(path)
            rotate = 360
            rotated_img = img
            while(rotate != 0):
                cv2.imshow('image',rotated_img)
                cv2.waitKey(0)
                cv2.destroyAllWindows()
                rotate = int(input("Rotate By: "))
                rotated_img = ndimage.rotate(img, rotate, reshape=False)
            #os.remove(path)
            cv2.imwrite(path, rotated_img)
            print(file.name + " saved")

After running this code over two photos and terminating normally I reopen the image files and they are 100% unchanged.


Solution

  • I'm not used to opencv but I think the problem is in this line

    cv2.imwrite(path, rotated_img)
    

    It must be put inside the while loop so that when the image is rotated by rotated_img = ndimage.rotate(img, rotate, reshape=False), it is written (saved). If it's not, your rotated_img will remain the same, as rotate = 0 when it exits the while loop.

    Also, if you want to save all rotated images, you should consider changing the path, for example: path = path + str(i), where i is increased by 1.

    i = 0
    while(rotate != 0):
        cv2.imshow('image',rotated_img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        rotate = int(input("Rotate By: "))
        rotated_img = ndimage.rotate(img, rotate, reshape=False)
        i += 1
        path_of_rotated_image = path + str(i)
        cv2.imwrite(path_of_rotated_image, rotated_img)
        print(file.name + " saved") # if you want to print