Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何打印出一张图片的平均像素?_Python_Python Imaging Library - Fatal编程技术网

Python 如何打印出一张图片的平均像素?

Python 如何打印出一张图片的平均像素?,python,python-imaging-library,Python,Python Imaging Library,下面是我的代码,我想用PIL中的.averagePixels代码打印平均像素,但输出返回'int'对象不可编辑。任何人都可以帮忙 from PIL import Image class PixelCounter(object): def __init__(self, imageName): self.pic = Image.open(imageName) self.imgData = self.pic.load() def averagePixel

下面是我的代码,我想用PIL中的.averagePixels代码打印平均像素,但输出返回'int'对象不可编辑。任何人都可以帮忙

from PIL import Image
class PixelCounter(object):
    def __init__(self, imageName):
        self.pic = Image.open(imageName)
        self.imgData = self.pic.load()
    def averagePixels(self):
        r, g, b = 0, 0, 0
        count = 0
        for x in range(self.pic.size[0]):
            for y in range(self.pic.size[1]):
                tempr,tempg,clrs = self.imgData[x,y]
                r += clrs[0]
                g += clrs[1]
                b += clrs[2]
                count += 1
        yield ((r/count)(g/count),(b/count), count)

if __name__ == '__main__':

    x=[]

    pc = PixelCounter(r"C:\Users\lena-gs.png")
    print ("(red, green, blue, total_pixel_count)")
    print (list(pc.averagePixels()))
输出为:

 (red, green, blue, total_pixel_count)
 TypeError  Traceback (most recent call last)
 <ipython-input-121-4b7fee4299ad> in <module>()
 19     pc = PixelCounter(r"C:\Users\user\Desktop\lena-gs.png")
 20     print ("(red, green, blue, total_pixel_count)")
 ---> 21     print (list(pc.averagePixels()))
 22 
 23 

 <ipython-input-121-4b7fee4299ad> in averagePixels(self)
  9         for x in range(self.pic.size[0]):
 10             for y in range(self.pic.size[1]):
 ---> 11                 tempr,tempg,clrs = self.imgData[x,y]
 12                 r += clrs[0]
 13                 g += clrs[1]

 TypeError: 'int' object is not iterable
(红、绿、蓝、总像素数)
TypeError回溯(最近一次调用上次)
在()
19 pc=PixelCounter(r“C:\Users\user\Desktop\lena gs.png”)
20打印(“红、绿、蓝、总像素数”)
--->21打印(列表(pc.averagePixels())
22
23
平均像素(自身)
范围内x为9(自拍尺寸[0]):
范围内y为10(自拍尺寸[1]):
--->11 tempr,tempg,clrs=self.imgData[x,y]
12 r+=clrs[0]
13 g+=clrs[1]
TypeError:“int”对象不可编辑

之所以发生这种情况,是因为
self.imgData[x,y]
是一个
int
,而不是可以分解为三个变量的东西;也就是说,如果您尝试执行类似
a、b、c=2
的操作,也会出现相同的错误。由于您的图像名为
lena gs.png
,我认为这可能是因为您使用的是没有alpha通道的灰度图像:

In [16]: pic = Image.open('test.png')

In [17]: data = pic.load()

In [18]: data[0, 0]
Out[18]: (44, 83, 140, 255)

In [19]: pic = Image.open('test-grayscale-with-alpha.png')

In [20]: data = pic.load()

In [21]: data[0, 0]
Out[21]: (92, 255)

In [33]: pic = Image.open('test-grayscale-without-alpha.png')

In [35]: data = pic.load()

In [36]: data[0, 0]
Out[36]: 92

不同类型的图像具有不同类型的像素。RGB图像每像素有三个*通道,但灰度图像只有一个*。通过将像素数据转换为Numpy数组并使用Numpy方法计算平均值,您可以以合理稳健的方式重写函数:

import numpy as np

pic = ... # An RGB image
picgs = ... # A grayscale image

def averagePixels(pic):
    if pic.mode=='L':
        return [np.array(pic).mean()]
    elif pic.mode=='RGB':
        pixData = np.array(pic)
        return [pixData[:,:,i].mean() for i in range(3)]
    else:
        raise Exception("Unsupported mode")

averagePixels(pic)
#[207.66529079861112, 199.11387297453703, 217.20738715277778]
averagePixels(picgs)
#[91.41583665338645]

*可以添加另一个通道来处理透明度

@tfirici在
(r/count)(g/count)
处也有一个错误。这应该无法运行。请确保您的代码可以运行,并准确地复制您认为应该运行的代码。正如您自己的示例所示,
self.imgData[x,y]
不是int而是tuple。@DYZ:Fair,我使用了一个带有alpha通道的示例。让我添加一个没有的示例。@fuglede这正是我想要的,thanks@tfirinci:太好了,如果你觉得答案有帮助,你可以。