Python 图像库 : image saved after pixel manipulation is always white

标签 python image

我有以下代码。 src_img 是 1250x1250 rgb 图像。我想创建另一个具有平均强度的灰度图像。

from PIL import Image

img = Image.open(src_img)
width, height = img.size
avg_img = Image.new('1', img.size, 'black')

avg_pixels = avg_img.load()

for x in range(width):
    for y in range(height):
        r, g, b = img.getpixel((x, y))
        avg_pixels[x, y] = int((r + g + b) / 3.0)

avg_img.save('avg.tiff')

但是生成的 avg.tiff 文件是纯白色的。我可以看到 avg_pixels 具有必要的值,但保存的图像与这些值不对应。

最佳答案

模式“1”是二值图像 - 表示白色或黑色。对于灰度,您需要“L”。

avg_img = Image.new('L', img.size, 'black')

关于Python 图像库 : image saved after pixel manipulation is always white,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17888559/

相关文章:

python - 我不能得到?而不是 %s 来处理 python mysqldb 的插入

html - 需要在 div 中垂直居中图像,但此处找到的答案不起作用

ios - 部分屏幕截图和图像质量损失

android - 在 Android 应用程序中使用图像和视频(Sqlite blob?)

C# ImageFormat 到字符串

Python-docx:是否可以在特定位置(不是末尾)向段落添加新的运行

python - python `with`语句用法的其他内置或实际示例?

python - 用定点迭代求解这个方程

python - Pandas :如何计算来自其他地方的人口百分比

html - 在文本中 float 图像