[英]Python: AttributeError: 'tuple' object has no attribute 'read'
我遇到了一個以前可以正常運行的程序的錯誤。 文件夾xxx_xxx_xxx包含許多jpeg格式的圖像文件。
我正在嘗試遍歷每個圖像並檢索每個圖像上每個像素的色相值。
我已經嘗試過這里提出的解決方案: Python-AttributeError:“ tuple”對象沒有屬性“ read”,而在這里: AttributeError:“ tuple”對象沒有屬性“ 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'
我不知道這段代碼以前是如何工作的(特別是如果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.
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.