为什么我的旋转图像无法正确保存?

时间:2019-06-18 17:07:43

标签: python image rotation overwrite ndimage

我需要旋转150张不同数量的图像,以便可以使用边界框正确注释我的数据。问题是由于某种原因,在运行我的代码并输入一些值之后,图像文件没有被旋转保存。如何以旋转方式保存这些图像,以便当我重新打开已旋转的图像文件时?

鉴于我实际上已经完全删除了文件并以相同的名称保存了一个新文件,因此应该正确覆盖该文件。

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

在两张照片上运行此代码并正常终止后,我重新打开图像文件,它们保持100%不变。

1 个答案:

答案 0 :(得分:0)

我不习惯使用opencv,但我认为问题出在这行

cv2.imwrite(path, rotated_img)

必须将其放在while循环内,以便在图像旋转rotated_img = ndimage.rotate(img, rotate, reshape=False)时被写入(保存)。如果不是,那么您的rotated_img会与rotate = 0保持不变,因为它退出了while循环。

此外,如果要保存所有 个旋转的图像,则应考虑更改path,例如:path = path + str(i),其中i增加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
相关问题