2016-12-27 37 views
-1

我可以加載圖像,如果我硬編碼的路徑,但是當我嘗試從列表中拿起字符串我不斷收到錯誤消息。不知道我在做什麼錯。從列表的文件路徑將不會加載python

#for i in range(0,len(training_YFT)): 
    #print(training_YFT[i]) 
#image = Image.open("/media/rafael/Data1/train/YFT/img_00004.jpg") 
image = Image.open(training_YFT[0]) 
#image = Image.open(training_YFT[i]).convert("L") 
arr = np.asarray(image) 
plt.imshow(arr, cmap='gray') 
plt.pause(0.01) 
plt.show() 

我貼在我得到的錯誤消息下面。 ñ

Traceback (most recent call last): 
    File "/home/rafael/anaconda3/lib/python3.5/site-packages/PIL/Image.py", line 2283, in open 
    fp.seek(0) 
AttributeError: 'str' object has no attribute 'seek' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
    File "fishy.py", line 95, in <module> 
    image = Image.open(training_YFT[0]) 
    File "/home/rafael/anaconda3/lib/python3.5/site-packages/PIL/Image.py", line 2285, in open 
    fp = io.BytesIO(fp.read()) 
AttributeError: 'str' object has no attribute 'read' 
+2

很奇怪。你可以執行一個'dir(training_YFT [0])並顯示結果嗎? –

+0

感謝發現問題列表中的第一個元素是空的。 –

+0

我用一個空字符串測試了它,並且如預期的那樣「沒有這樣的文件或目錄」消息。奇怪(我相信你,因爲這些消息指出一個'str'對象已經通過,但是應該試圖打開這個文件,而不是去尋找它) –

回答

-1
Traceback (most recent call last): 
    File "/home/rafael/anaconda3/lib/python3.5/site-packages/PIL/Image.py", line 2283, in open 
    fp.seek(0) 
AttributeError: 'str' object has no attribute 'seek' 

所以第一個錯誤是,你要調用的對象是file對象,但變量實際上是一個字符串對象。

而且str對象沒有被調用函數求

所以移動到列表中的問題。

嘗試打印出清單,以確保它不是一個str

['path1', 'path2']

,如果它確實是一個列表,它應該返回給你path1

,如果它是一個字符串,它將返回p,這不是你想要的

接下來,它看起來像Image類想要一個文件對象,並且你傳遞給它一個字符串。雖然很奇怪,但你之前通過了一個字符串,它似乎工作。我的建議是嘗試Image.open(open(variable))

AttributeError: 'str' object has no attribute 'read'

我從來沒玩過與PIL包,但是,你能做的最好的事情是打印之前和之後函數的變量,確保它們的變量,你」 d喜歡通過

print(training_YFT) 
if not type(training_YFT) == list: print('training_YFT IS NOT A LIST, you\'re giving the function '+training_YET[0]+'!') 
image = Image.open(training_YFT[0]) 
print(image) 
arr = np.asarray(image) 
plt.imshow(arr, cmap='gray') 
plt.pause(0.01) 
plt.show() 

另一個建議是確保文件路徑的存在。你可以通過導入os.path isfile來做到這一點。例如from os.path import isfile

由於沒有足夠的信息來準確確定沒有所有源代碼,因此無法準確告訴您代碼出了什麼問題。但我希望這能幫助你,並給你一些想法,以便在事情沒有奏效的時候嘗試。

+0

如果你看看PIL文檔,它們似乎表明通過一個字符串或一個文件是好的。 –

相關問題