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

标签 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 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

最佳答案

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

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

关于python - 如何打印出一张图片的平均像素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54496673/

相关文章:

python - 无法从正在运行的进程读取标准输出

Python Ctypes 注册回调函数

python - 如何在 Windows 中使用 ffmpeg 抓取笔记本电脑网络摄像头视频

python - 在使用 `types.new_class` 创建的类上设置模块

python - 为什么 ImageStat 返回有符号整数图像 (`mode=' I'`) 的错误统计信息?

python - 列中除某些词外的标题词

python - 使用 OpenCV 将一定范围内的颜色更改为另一种颜色

python-imaging-library - 由于我安装了 MACOS Catalina,预览应用程序无法打开

python - PIL : image from url, 无法识别镜像文件

python - PIL image.resize larger and then smaller 返回相同的图像吗?