Windows终端运行matplotlib时fig.canvas.tostring_rgb返回字节长度错误
你遇到的字节长度不匹配问题,是Windows系统高DPI缩放和matplotlib默认GUI后端的自动适配机制共同导致的。你遇到的实际字节长度是预期的4倍,对应系统DPI缩放比例为200%:matplotlib会跟随系统缩放将画布实际渲染分辨率放大2倍,但是fig.canvas.get_width_height()返回的是未缩放的逻辑尺寸,二者不匹配就会导致reshape失败。
Windows端Jupyter使用的inline后端、Linux环境默认不触发这种GUI级别的DPI适配,所以运行正常。
可用解决方案
方案1:切换无GUI的Agg后端,彻底规避系统缩放影响
代码最开头设置后端即可:import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np方案2:创建画布时固定dpi,禁用自动适配
替换创建画布的代码,明确指定dpi为Windows系统基础值96:fig = plt.figure(dpi=96)方案3:根据实际字节长度反推维度,兼容所有缩放场景
不需要修改前置代码,仅调整reshape逻辑:import matplotlib.pyplot as plt import numpy as np fig = plt.figure() fig.tight_layout(pad=0) fig.canvas.draw() data = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8) # 计算实际缩放比例 logic_w, logic_h = fig.canvas.get_width_height() scale = int(np.sqrt(len(data) / (logic_w * logic_h * 3))) # 按实际渲染尺寸reshape data = data.reshape((logic_h * scale, logic_w * scale, 3))
内容的提问来源于stack exchange,提问作者xinwei li
相关产品推荐
相关产品推荐

