Python:属性错误:'tuple'对象没有属性'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.
            .

最新更新