2016-10-26 48 views
-2

好的,所以我需要在我的導師自己的單詞中: - 讀取圖像目錄中的所有圖像 - 創建每個圖像的直方圖。你的直方圖功能不能使用PIL函數Image.historgam。遇到路徑問題

我有了這個基本的代碼至今:

from os import listdir 
from PIL import Image as PImage 

def loadImages(path): 
    imagesList = listdir(path) 
    loadedImages = [] 
    for image in imagesList: 
     img = PImage.open(path + image) 
     loadedImages.append(img) 
    return loadedImages 
path = "/ 

imgs = loadImages(path) 

for img in imgs: 
    img.show() 

這個問題是路徑= /位。我不知道如何正確輸入,以便程序從我的桌面(或其他任何可以放入它的地方)讀取一個名爲「images」的文件。

請儘快回覆,我不能在我的任務中取得進展,直到我這樣做。

+1

你沒有提到什麼地方出了錯,當你運行你的代碼。這是找出問題所在的重要部分。順便說一句,打印是你的朋友。在你的for循環中打印(路徑+圖像)'看看你得到了什麼。 – tdelaney

+0

「問題在於路徑= /位,我不知道如何正確輸入,以便程序從我的桌面(或其他任何可以推薦的位置)讀取名爲」圖像「的文件。」 –

+0

您的代碼讀取目錄中的所有圖像,但您說要讀取一個名爲「images」的文件。混亂! – tdelaney

回答

0

您應該使用os.path來處理文件路徑。

import os 

for filename in filelist: 
    full_path = os.path.join(path, filename) 

您還應該考慮os.listdir還在其結果中包含目錄。此外,在您定義path的代碼中可能存在錯誤,您似乎錯過了結束語。

+0

我的問題是我不知道我的路徑或文件列表是什麼。這沒有奏效。它導致了文字錯誤。 –

+0

如果你不知道它們在哪裏,你打算如何打開文件? 'path'應該是''/ path/to/mypics'','filelist'應該是'os.listdir(path)' – sytech

0

使用os.path.join(path, filename)創建文件路徑:

import os 
import os.path 
from PIL import * 

def loadImages(path): 
    return [PImage.open(os.path.join(path, image)) for image in os.listdir(path)] 

for img in loadImages('/'): 
    img.show() 
+0

我不能使用PIL作爲直方圖,我仍然不知道從我學校的時間開車路徑。 –

+0

轉到與照片的文件夾,右鍵單擊其中一張照片,單擊'屬性',看看'位置'是 – Uriel

+0

謝謝你烏列爾!我會嘗試的! –

0

這裏是

  • 提示用戶輸入的路徑掃描
  • 使用os.path.join來構建文件的解決方案名稱
  • 過濾出子目錄名稱
  • 捕獲PIL錯誤

我認爲它涵蓋了原來的要求

import os 
from PIL import Image as PImage 

def loadImages(path): 
    # paths to files in directory with non-files filtered out 
    images = filter(os.path.isfile, (os.path.join(path, name) 
     for name in os.listdir(path))) 
    loadedImages = [] 
    for image in images: 
     try: 
      loadedImages.append(PImage.open(image)) 
      print("{} is an image file".format(image)) 
     except OSError: 
      # exception raised when PIL decides this is not an image file 
      print("{} is not an image file".format(image)) 
    return loadedImages 

while True: 
    path = input("Input image path: ") 
    # expand env vars and home directory tilda 
    path = os.path.expanduser(os.path.expandvars(path)) 
    # check for bad input 
    if os.path.isdir(path): 
     break 
    print("Not a directory. Try again.") 

imgs = loadImages(path) 

for img in imgs: 
    img.show()