由于您没有回答我的最后一个追问,我做了一些猜测并实现了一些东西,以说明如何仅使用PIL
(或pillow
)模块完成它。
简而言之,该代码将图像转换为灰度,将结果为0%至100%亮度(强度)的像素范围分成相等大小的子范围,然后为每个子范围分配来自调色板的颜色。
from PIL import Image
from PIL.ImageColor import getcolor, getrgb
from PIL.ImageOps import grayscale
try:
xrange
except NameError:
xrange = range
def falsecolor(src, colors):
if Image.isStringType(src):
src = Image.open(src)
if src.mode not in ['L', 'RGB', 'RGBA']:
raise TypeError('Unsupported source image mode: {}'.format(src.mode))
src.load()
num_colors = len(colors)
palette = [colors[int(i/256.*num_colors)] for i in xrange(256)]
luts = (tuple(c[0] for c in palette) +
tuple(c[1] for c in palette) +
tuple(c[2] for c in palette))
l = src if Image.getmodebands(src.mode) == 1 else grayscale(src)
if Image.getmodebands(src.mode) < 4:
merge_args = ('RGB', (l, l, l))
else:
a = Image.new('L', src.size)
a.putdata(src.getdata(3))
luts += tuple(xrange(256))
merge_args = ('RGBA', (l, l, l, a))
return Image.merge(*merge_args).point(luts)
if __name__ == '__main__':
R, G, B = (255, 0, 0), ( 0, 255, 0), ( 0, 0, 255)
C, M, Y = ( 0, 255, 255), (255, 0, 255), (255, 255, 0)
filename = 'test_image.png'
falsecolor(filename, [B, R, G, Y]).show()
下面是一个组合图像,显示一个RGB测试图像,中间的内部256级灰度图像,以及将其转换为由四种颜色组成的伪彩色图像的最终结果(每种颜色代表64个强度级别的范围):
![before, intermediate, and after images](https://istack.dev59.com/odDal.webp)
这是另一个复合图像,只不过这次展示的是将已经变成灰度的图像转换为相同的4种虚假颜色调色板。
![example of grayscale to false color image conversion](https://istack.dev59.com/LO284.webp)
像这样做是否符合您的要求?
cp
是什么?你想要什么样的效果最终呈现出来,能给个例子吗?这个链接或者链接是否相关或有帮助(即使不是Python)? - Matt Hall