我想使用PIL将一个文件转换为Python中的灰度,然后获得像素的x、y和rgb值,但我得到了一个错误.

代码:


from PIL import Image,ImageOps
file_name = "test.png"
og_image = Image.open(file_name)
gray_image = ImageOps.grayscale(og_image)
gray_scalefile = f"{file_name[:-3]}gray.png"
gray_image.save(gray_scalefile)
img = Image.open(gray_scalefile)
pixels = img.load() 
width, height = img.size
for x in range(width):
    for y in range(height):
        r, g, b = pixels[x, y]
        print(x, y, f"{r},{g},{b}")

contents of text.png: enter image description here

contents of text.gray.png: enter image description here

该代码可以很好地处理ext.png,但当我将其灰度化时,它就不能工作了,并给出了这个错误.

Traceback (most recent call last):
  File "d:\Image Manipulation\Image Manipulation.py", line 12, in <module>
    r, g, b = pixels[x, y]
TypeError: cannot unpack non-iterable int object

推荐答案

file_name = "test.jpg"
og_image = Image.open(file_name)
gray_image = ImageOps.grayscale(og_image)
gray_scalefile = f"{file_name[:-3]}gray.jpg"
gray_image.save(gray_scalefile)
img = Image.open(gray_scalefile).convert('RGB')
pixels = img.load()
width, height = img.size
for x in range(width):
    for y in range(height):
        r,g,b= pixels[x, y]
        print(x, y, f'{r},{g},{b}')

这将会起作用,因为它首先将发光转换为RGB

Python相关问答推荐

如何将双框框列中的成对变成两个新列

标题:如何在Python中使用嵌套饼图可视化分层数据?

无法通过python-jira访问jira工作日志(log)中的 comments

pandas滚动和窗口中有效观察的最大数量

使用@ guardlasses. guardlass和注释的Python继承

如何将多进程池声明为变量并将其导入到另一个Python文件

如何从pandas的rame类继承并使用filepath实例化

如何使用两个关键函数来排序一个多索引框架?

下三角形掩码与seaborn clustermap bug

人口全部乱序 - Python—Matplotlib—映射

用SymPy在Python中求解指数函数

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

将CSS链接到HTML文件的问题

如何从比较函数生成ngroup?

如何使用大量常量优化代码?

Python协议不兼容警告

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

PYTHON中的selenium不会打开 chromium URL

将像素信息写入文件并读取该文件

基于2级列表的Pandas 切片3级多索引