Python 如何使用cm.scalarMapable colormap数据中的颜色填充ImageDraw矩形(或椭圆)颜色?
我有一些dataframe,我正在基于dataframe中的x、y、维度和数据值构建一个矩形布局,如下所示:Python 如何使用cm.scalarMapable colormap数据中的颜色填充ImageDraw矩形(或椭圆)颜色?,python,image,python-imaging-library,colormap,Python,Image,Python Imaging Library,Colormap,我有一些dataframe,我正在基于dataframe中的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: 146376
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颜色数据以用于填充矩形?好的,我可能问这个问题太早了,我找到了答案:
mapper.to_rgba(data.loc[index,'ratio'],bytes=True)
中的“bytes”将被设置为True
,我在cm.ScalarMappable(norm=None,cmap=cm.tab20b)中设置了norm
,它应该是cm.ScalarMappable(norm=norm,cmap=cm.tab20b)
错误来自“…fill=mapper.to_rgba(…)”部分,因为它需要从0到255的rgba值。如何正确地将colormap值映射到0到255个rgba值?好的,mapper.to_rgba()
的类型是什么?