【问题标题】:How do I fill an ImageDraw rectangle (or ellipse) color with a color from cm.ScalarMappable colormap data?如何使用 cm.ScalarMappable 颜色图数据中的颜色填充 ImageDraw 矩形(或椭圆)颜色?
【发布时间】:2021-02-02 13:12:05
【问题描述】:

我有一些数据框,我正在根据数据框中的 x、y、维度和数据值构建矩形布局,如下所示:

import PIL.Image as Image, ImageDraw
from matplotlib import cm
import pandas as pd
import matplotlib

data={'index': {0: 0, 1: 1, 2: 2, 3: 3},
 'ratio': {0: 726242000000,1: 56200692307, 2: 146376666666,3: 143607000000},
 'x': {0: 750, 1: 2250, 2: 750, 3: 2250},
 'y': {0: 750, 1: 750, 2: 2250,3: 2250},
 'dimension': {0: 350, 1: 350, 2: 350, 3: 350}}
data=pd.DataFrame.from_dict(data)
minima = min(data.loc[:,'ratio'])
maxima = max(data.loc[:,'ratio'])
norm_ = matplotlib.colors.Normalize(vmin=minima, vmax=maxima, clip=True)
mapper = cm.ScalarMappable(norm=None, cmap=cm.tab20b)

image = Image.new('RGBA', (3000,3000), (255, 255, 255))
draw = ImageDraw.Draw(image)
for index, row in data.iterrows():
    x0= (data.loc[index,'x']-data.loc[index,'dimension']/2)
    y0= (data.loc[index,'y']-data.loc[index,'dimension']/2)
    x1= (data.loc[index,'x']+data.loc[index,'dimension']/2)
    y1= (data.loc[index,'y']+data.loc[index,'dimension']/2)
    draw.rectangle((x0,y0,x1,y1),fill=mapper.to_rgba(data.loc[index,'ratio']))

我收到以下错误:

TypeError: integer argument expected, got float

那么如何转换 cmap 颜色数据来填充矩形呢?

【问题讨论】:

  • 错误来自“...fill=mapper.to_rgba(...)”部分,因为它需要 rgba 值从 0 到 255。如何正确地将颜色映射值映射到0 到 255 个 rgba 值?
  • 好的,那么mapper.to_rgba()type 是什么,它看起来如何?

标签: python image python-imaging-library colormap


【解决方案1】:

好吧,我可能问得太早了,但我找到了答案:

mapper.to_rgba(data.loc[index,'ratio'],bytes=True) 中的“字节”将设置为True,而我在cm.ScalarMappable(norm=None, cmap=cm.tab20b) 中设置了norm,不小心设置了None,它应该是cm.ScalarMappable(norm=norm_, cmap=cm.tab20b)

【讨论】: