2015-08-08 496 views
1

我得到一個錯誤,以前沒有任何問題的工作的程序。 文件夾xxx_xxx_xxx包含許多jpeg格式的圖像文件。Python:AttributeError:'元組'對象沒有屬性'讀'

我試圖通過每個圖像運行並檢索每個圖像上的每個像素的色調值。

我試過這裏提出的解決方案:Python - AttributeError: 'tuple' object has no attribute 'read'和這裏:AttributeError: 'tuple' object has no attribute 'read'沒有成功。

代碼:

from PIL import Image 
import colorsys 
import os 

numberofPix = 0 
list = [] 
hueValues = 361 
hueRange = range(hueValues) 

for file in os.walk("c:/users/xxxx/xxx_xxx_xxx"): 
    im = Image.open(file) 
    width, height = im.size 
    rgb_im = im.convert('RGB') 

    widthRange = range(width) 
    heightRange = range(height) 

    for i in widthRange: 
     for j in heightRange: 
      r, g, b = rgb_im.getpixel((i, j)) 
      if r == g == b: 
       continue 
      h, s, v = colorsys.rgb_to_hsv(r/255.0, g/255.0, b/255.0) 
      h = h * 360 
      h = int(round(h)) 
      list.append(h) 
      numberofPix = numberofPix + 1 

for x in hueRange: 
    print "Number of hues with value " + str(x) + ":" + str(list.count(x)) 

print str(numberofPix) 

這裏是我得到的錯誤:

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

回答

1

我不知道這個代碼是如何曾任職(特別是如果該行 - for file in os.walk("c:/users/nathan/New_Screenshots_US/Dayum"):在那裏之前也) ,該行是您的問題的主要原因。

os.walk返回格式的元組 - (dirName, subDirs, fileNames) - 其中dirName是當前正在行走的目錄的名稱,fileNames是該特定目錄中文件的列表。

在你正在做的下一行 - im = Image.open(file) - 這不起作用,因爲file是一個元組(上述格式)。您需要遍歷每個文件名,如果文件是.jpeg,則需要使用os.path.join創建文件的路徑並在Image.open()中使用它。

實施例 -

from PIL import Image 
import colorsys 
import os 
import os.path 

numberofPix = 0 
list = [] 
hueValues = 361 
hueRange = range(hueValues) 

for (dirName, subDirs, fileNames) in os.walk("c:/users/nathan/New_Screenshots_US/Dayum"): 
    for file in fileNames: 
     if file.endswith('.jpeg'): 
      im = Image.open(os.path.join(dirName, file)) 
      . #Rest of the code here . Please make sure you indent them correctly inside the if block. 
      . 
相關問題