循环浏览图像目录并将它们全部旋转x度并保存到目录

Teo*_*off 2 python opencv image rotation scipy

我使用的是Python,Open,Numpy和Scipy.我有一个想要按特定角度旋转的图像目录.我想编写这个脚本.我正在使用这个,OpenCV Python围绕特定点旋转图像X度,但它似乎没有像我想象的那样完全管道.我得到了一个无效的轮换计划,但我不认为我应该得到这个.

这是我的代码的样子:

from scipy import ndimage
import numpy as np
import os
import cv2

def main():
    outPath = "C:\Miniconda\envs\.."
    path = "C:\Miniconda\envs\out\.."
    for image_to_rotate in os.listdir(path):
        rotated = ndimage.rotate(image_to_rotate, 45)
        fullpath = os.path.join(outPath, rotated)

  if __name__ == '__main__':
     main()
Run Code Online (Sandbox Code Playgroud)

小智 8

在旋转之前,您需要实际读取图像文件.您当前的代码正在做的只是迭代文件(和目录)的名称.

os.listdir(path)为您提供文件夹内容列表(基本上只是名称),然后您需要使用ndimage.imread()函数打开这些文件.

这应该工作:

from scipy import ndimage, misc
import numpy as np
import os
import cv2

def main():
    outPath = "C:\Miniconda\envs\.."
    path = "C:\Miniconda\envs\out\.."

    # iterate through the names of contents of the folder
    for image_path in os.listdir(path):

        # create the full input path and read the file
        input_path = os.path.join(path, image_path)
        image_to_rotate = ndimage.imread(input_path)

        # rotate the image
        rotated = ndimage.rotate(image_to_rotate, 45)

        # create full output path, 'example.jpg' 
        # becomes 'rotate_example.jpg', save the file to disk
        fullpath = os.path.join(outPath, 'rotated_'+image_path)
        misc.imsave(fullpath, rotated)

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

PS:这种迭代文件夹内容的方式只有在目录中只有文件且没有子目录时才有效.os.listdir(path)将返回任何文件和子目录的名称.

您可以从这篇文章中学习如何仅列出目录中的文件:如何列出目录的所有文件?