更新答案
看来Pillow 也可以从您的 TIFF 中提取调色板。我不是 Python 专家,但我写了这个并且它似乎有效:
from PIL import Image
image = Image.open('indexed.tif')
print(image.getpalette()[:12])
输出
[0, 0, 0, 140, 215, 115, 255, 255, 255, 0, 0, 0]
原答案
您可以使用 ImageMagick 在命令行中轻松完成您所要求的操作,该软件安装在大多数 Linux 发行版上,适用于 macOS 和 Windows。
先回答最后一部分,可以用这个命令提取调色板:
identify -verbose indexed.tif
样本输出
Image: indexed.tif
Format: TIFF (Tagged Image File Format)
Mime type: image/tiff
Class: PseudoClass
Geometry: 1024x1024+0+0
Resolution: 72x72
Print size: 14.2222x14.2222
Units: PixelsPerInch
Colorspace: sRGB
Type: Palette
Endianess: LSB
Depth: 8-bit
Channel depth:
Red: 8-bit
Green: 8-bit
Blue: 8-bit
Channel statistics:
Pixels: 1048576
Red:
min: 0 (0)
max: 140 (0.54902)
mean: 24.9271 (0.0977535)
standard deviation: 53.5578 (0.210031)
kurtosis: 0.832982
skewness: 1.68315
entropy: 0.675795
Green:
min: 0 (0)
max: 215 (0.843137)
mean: 38.281 (0.150121)
standard deviation: 82.2495 (0.322547)
kurtosis: 0.832982
skewness: 1.68315
entropy: 0.675795
Blue:
min: 0 (0)
max: 115 (0.45098)
mean: 20.4759 (0.0802975)
standard deviation: 43.9939 (0.172525)
kurtosis: 0.832982
skewness: 1.68315
entropy: 0.675795
Image statistics:
Overall:
min: 0 (0)
max: 215 (0.843137)
mean: 27.8947 (0.109391)
standard deviation: 59.9337 (0.235034)
kurtosis: 2.61693
skewness: 2.01681
entropy: 0.675795
Colors: 2
Histogram:
861876: ( 0, 0, 0) #000000 black
186700: (140,215,115) #8CD773 srgb(140,215,115)
Colormap entries: 256
Colormap:
0: ( 0, 0, 0,255) #000000FF black
1: (140,215,115,255) #8CD773FF srgba(140,215,115,1)
2: (255,255,255,255) #FFFFFFFF white
3: ( 0, 0, 0,255) #000000FF black
4: ( 0, 0, 0,255) #000000FF black
5: ( 0, 0, 0,255) #000000FF black
6: ( 0, 0, 0,255) #000000FF black
7: ( 0, 0, 0,255) #000000FF black
8: ( 0, 0, 0,255) #000000FF black
...
...
您可以在上面的最后 8 行中看到您的调色板(颜色图)。更方便的命令是:
identify -verbose indexed.tif | grep -A8 "Colormap:"
Colormap:
0: ( 0, 0, 0,255) #000000FF black
1: (140,215,115,255) #8CD773FF srgba(140,215,115,1)
2: (255,255,255,255) #FFFFFFFF white
3: ( 0, 0, 0,255) #000000FF black
4: ( 0, 0, 0,255) #000000FF black
5: ( 0, 0, 0,255) #000000FF black
6: ( 0, 0, 0,255) #000000FF black
7: ( 0, 0, 0,255) #000000FF black
现在是您问题的第一部分。为黑色和其他颜色获取零图像的最简单方法是将填充颜色设置为 1(ImageMagick 调用 gray(1)),然后将非黑色的所有内容设置为那个颜色。最后,另存为 PGM(便携式 GreyMap)文件,OpenCV 可以在没有任何库的情况下读取该文件,并且不能包含调色板,因此它不会让你乱七八糟:
convert indexed.tif -fill "gray(1)" +opaque black indices.pgm
这就是实际答案的结尾。以下只是额外的信息。
请注意,这将是一张非常暗、对比度低的图像,因为它仅包含 0-255 范围内的 0 或 1,因此您需要对其进行标准化或对比度拉伸什么都看:
convert indices.pgm -normalize result.jpg
请注意,如果您使用 ImageMagick v7+,identify 在上述命令中将变为 magick identify,convert 将变为 magick。