2017-02-06 62 views
0

我正在使用Python,Open,Numpy和Scipy。我有一個我想旋轉某些角度的圖像目錄。我想編寫這個腳本。我正在使用這個,OpenCV Python rotate image by X degrees around specific point,但它似乎沒有像我設想的那樣流暢。我得到一個無效的輪換計劃,但我不認爲我應該得到這個。循環遍歷圖像目錄並將它們全部旋轉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() 

回答

5

您需要旋轉這些之前,實際讀取的圖像文件。你目前的代碼正在做什麼只是迭代文件(和目錄)的名稱。

os.listdir(路徑)給你的文件夾(基本上只是名稱)的內容列表,然後你需要使用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() 

PS:通過只如果只有在目錄中沒有子目錄中的文件的工作文件夾的內容進行迭代的這種方式。 os.listdir(路徑)將返回任何文件的名稱以及子目錄。

您可以在此文章中學習如何僅列出目錄中的文件:How to list all files of a directory?

相關問題