Python Pil 将 GreyScale Tif 转换为 RGB

标签 python python-imaging-library rgb grayscale

我有一个灰度 TIF 文件。我需要将它转换为 RGB/以我可以使用它的方式从中读取。

img = Image.open(GIF_FILENAME)
rgbimg = img.convert('RGB')
for i in range(5):
    print rgbimg.getpixel((i, 0))

convert.("RGB") 将自动生成所有内容 (255,255,255),即使图片是一张非常暗且主要是黑色的图片。

如果我只读取灰度数字,我会得到大约 1400 到 1900 之间的数字。

我还需要将图片的副本另存为 RGB Jpeg。 问题图片:[这里]:http://imgur.com/kEwfFs3

我该怎么做?

最佳答案

关于:

img = Image.open(GIF_FILENAME)
rgbimg = Image.new("RGBA", img.size)
rgbimg.paste(img)
rgbimg.save('foo.jpg')

[编辑]

创建了一个测试:

from PIL import Image
from collections import defaultdict
import pprint

img = Image.open("kEwfFs3.png")
rgbimg = Image.new("RGBA", img.size)
rgbimg.paste(img)

found_colors = defaultdict(int)
for x in range(0, rgbimg.size[0]):
    for y in range(0, rgbimg.size[1]):
        pix_val = rgbimg.getpixel((x, y))
        found_colors[pix_val] += 1 
pprint.pprint(dict(found_colors))

rgbimg.save('kEwfFs3.jpg')

然后输出:

{(0, 0, 0, 255): 747802,
 (1, 1, 1, 255): 397,
 (2, 2, 2, 255): 299,
 (3, 3, 3, 255): 255,
 (4, 4, 4, 255): 221,
 (5, 5, 5, 255): 200,
 (6, 6, 6, 255): 187,
 (7, 7, 7, 255): 138,
 (8, 8, 8, 255): 160,
 (9, 9, 9, 255): 152,
 (10, 10, 10, 255): 122,
 (11, 11, 11, 255): 116,
 (12, 12, 12, 255): 144,
 (13, 13, 13, 255): 117,
 (14, 14, 14, 255): 117,
 (15, 15, 15, 255): 102,
 (16, 16, 16, 255): 119,
 (17, 17, 17, 255): 299641,
 (18, 18, 18, 255): 273,
 (19, 19, 19, 255): 233,
.................... etc .......
.................... etc .......
 (249, 249, 249, 255): 616,
 (250, 250, 250, 255): 656,
 (251, 251, 251, 255): 862,
 (252, 252, 252, 255): 1109,
 (253, 253, 253, 255): 1648,
 (254, 254, 254, 255): 2964175}

这是您所期望的。 你的输出不同吗?

关于Python Pil 将 GreyScale Tif 转换为 RGB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18522295/

相关文章:

visual-studio - .vssettings 文件(Visual Studio 设置)颜色格式

opencv - 有没有一种直接的方法可以在 opencv C++ 中获取表示 RGB 颜色的唯一值

python - 向导的替代品

python - SQLAlchemy 插入executemany 函数

python - 裁剪时在 PIL 中保留图像类型信息

python - 如何同时给图片添加对比度、亮度等多种效果

c# - 如何将RGB相机图像转换为SharpDX的ARGB格式?

python - 当我使用 torch.nn.CrossEntropyLoss 时,我是否必须在 def front 中添加 softmax

python - 在图像上绘制线条与坐标不匹配。 Python

python - 如何通过电报机器人发送 PIL 图像而不将其保存到文件中