灰度热图到颜色梯度热图



我试图采取一组256x256px 8位灰度。png(透明度),并将灰度。png转换为相同大小的彩色。png,仍然保持透明度。我想使用的调色板是来自Rwesanderson包的Zissou1,我已经将其放入Python字典中,其中每个键对应一个灰度值,每个值对应一个HEX颜色。

import os
from PIL import Image, ImageColor
### dic = the dictionary containing the palette in format {grayscale pixel value: "HEX COLOR"},
###       created earlier in the script
with Image.open("3.png") as im:
fin = Image.new("RGBA", im.size)
px = im.load()
px1 = fin.load()
for x in range(0,256):
for y in range(0,256):
px1.putpixel(x,y,ImageColor.getcolor(dic[px.getpixel(x,y)[1]],"RGBA"))
fin.show()

我得到错误:

px1.putpixel(x,y,ImageColor.getcolor(dic[px.getpixel(x,y)[1]],"RGBA"))
AttributeError: 'PixelAccess' object has no attribute 'putpixel'

延续Jason的回答:

PIL

给出的查找使用Image.point(lookup_table, mode = 'L'),您可以查找和调换图像的颜色。

lookup_table = ...
with Image.open("3.png") as orig:
image = orig.point(lookup_table, mode = 'L')
image.show()

查看对lookup_table使用Image.point方法的示例:

  • 在PIL中使用Image.point()方法操作像素数据

您自己的实现(修复了改进的命名)

或者自己实现对your_dic的查找:

your_dic = ...
with Image.open("3.png") as orig:
image = colored_from_map(orig, your_dic)
image.show()

使用这个可选函数(您几乎这样做了):

def colored_from_map(orig, map_to_color):
image_in = orig.load()
image = Image.new("RGBA", im.size)
image_out = image.load()
for x in range(0,256):
for y in range(0,256):
coords = (x,y)
greyscale = image_in.getpixel(x,y)[1]
color_name = map_to_color[greyscale]
image_out.putpixel(coords, ImageColor.getcolor(color_name,"RGBA"))
return image

保留alpha通道(透明度)

参见ImageColor.getColor()的源代码在其方法体的开始和结束处:

color, alpha = getrgb(color), 255  # default to no-transparency
if len(color) == 4:  # if your mapped color has 4th part as alpha-channel
color, alpha = color[0:3], color[3]  # then use it
# omitted lines
else:
if mode[-1] == "A":  # if the last char of `RGBA` is `A`
return color + (alpha,)  # then return with added alpha-channel
return color

(评论我的)

因此,您可以简单地将返回的颜色元组的第四个元素设置为原始灰度图像的前一个值:
greyscale = image_in.getpixel(x,y)[1]  # containing original alpha-channel
color_name = map_to_color[greyscale]  # name or hex
mapped_color = ImageColor.getcolor(color_name,"RGB")  # removed the A
transposed_color = mapped_color[:2] + (greyscale[3],)  # first 3 for RGB + original 4th for alpha-channel (transparency)
image_out.putpixel(coords, transposed_color)

注意:因为A(alpha通道)是从原始图像中提供的,所以我从getColor调用的最后一个参数中删除了A。从技术上讲,您也可以从mapped_color[:2]中删除切片,从而得到mapped_color + (greyscale[3],)

PIL的PixelAccess.putpixel方法的第一个参数期望像素的坐标以(x,y)元组的形式传递:

px1.putpixel((x,y),ImageColor.getcolor(dic[px.getpixel(x,y)[1]],"RGBA"))

或者,考虑使用Image。点方法,它需要一个类似于您已经创建的查找表,以基于像素值映射图像。有关详细信息,请参阅在PIL中使用Image.point()方法来操作像素数据

最新更新