You need to enable JavaScript to run this app. 如何将matplotlib cm.ScalarMappable颜色转换为PIL ImageDraw合法填充值
优惠活动
大模型
产品
解决方案
定价
更多

如何将matplotlib cm.ScalarMappable颜色转换为PIL ImageDraw合法填充值

报错根因定位

两个直接触发报错的核心原因,搭配一个影响实际效果的隐藏逻辑错误:

  • 坐标类型不匹配:ImageDraw的矩形绘制接口要求传入的四个边界坐标必须为整数类型,但代码中通过dimension/2计算得到的坐标为浮点数(如175.0),直接传入就会触发整数参数类型错误
  • 颜色格式不匹配:matplotlib的ScalarMappable.to_rgba()默认返回0~1区间的浮点型RGBA值(类似(0.32, 0.56, 0.89, 1.0)),而PIL的图形填充参数要求的是0~255取值范围的8位整数型RGBA元组,格式完全不兼容
  • 隐藏映射bug:初始化ScalarMappable时将norm参数设为None,之前定义的norm_归一化规则完全没有被加载,即使解决了类型报错,颜色映射结果也是错的
适配修正方案
  • 坐标计算完成后,统一将四个边界值通过int()转换为整数类型,符合PIL的接口要求
  • 拿到matplotlib返回的归一化RGBA值后,将每个通道值乘以255,再转换为整数,拼接成符合PIL要求的颜色元组
  • 初始化ScalarMappable时,将预先定义的norm_作为norm参数传入,保证数值到颜色的映射逻辑正常生效
修正后可直接运行的代码
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)
# 修正:传入自定义的norm实例
mapper = cm.ScalarMappable(norm=norm_, cmap=cm.tab20b)

image = Image.new('RGBA', (3000,3000), (255, 255, 255, 255))
draw = ImageDraw.Draw(image)
for index, row in data.iterrows():
    # 修正:坐标计算后转整数
    x0 = int(row['x'] - row['dimension']/2)
    y0 = int(row['y'] - row['dimension']/2)
    x1 = int(row['x'] + row['dimension']/2)
    y1 = int(row['y'] + row['dimension']/2)
    # 修正:转换matplotlib输出的浮点RGBA为PIL兼容的整数RGBA
    rgba_float = mapper.to_rgba(row['ratio'])
    fill_color = tuple(int(channel * 255) for channel in rgba_float)
    draw.rectangle((x0,y0,x1,y1), fill=fill_color)
通用说明
  • 这套颜色转换逻辑对椭圆、线段、多边形等所有ImageDraw的绘图接口都通用,不需要单独调整
  • 如果需要保留自定义透明度效果,转换时直接对alpha通道做相同的乘255转整数操作即可,不需要额外修改逻辑

内容的提问来源于stack exchange,提问作者Harshad Surdi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.21 14:36:04