[英]Grayscale Heatmap to Color Gradient Heatmap
我正在嘗試采用一組 256x256px 8 位灰度 .png(具有透明度)並將灰度 .png 轉換為相同大小的顏色 .png,但仍保持透明度。 我想使用的調色板是來自 R wesanderson
包的 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'
PIL 的PixelAccess.putpixel
方法的第一個參數期望像素的坐標作為 (x,y) 元組傳遞:
px1.putpixel((x,y),ImageColor.getcolor(dic[px.getpixel(x,y)[1]],"RGBA"))
或者,考慮使用Image.point方法,該方法采用類似於您已經創建的查找表的查找表,以根據像素值映射圖像。 有關更多詳細信息,請參閱使用 PIL 中的 Image.point() 方法操作像素數據中的答案
擴展傑森的回答:
使用Image.point(lookup_table, mode = 'L')
您可以查找和轉置圖像的顏色。
lookup_table = ...
with Image.open("3.png") as orig:
image = orig.point(lookup_table, mode = 'L')
image.show()
要查看將Image.point
方法與lookup_table
一起使用的示例:
或自己實現對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
請參閱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(lpha-channel) 是從原始圖像提供的,所以我從getColor
調用的最后一個參數中刪除了A
從技術上講,您還可以從mapped_color[:2]
中刪除切片以mapped_color + (greyscale[3],)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.