You need to enable JavaScript to run this app. 使用matplotlib绘制specgram时自定义figsize触发内存不足错误
优惠活动
大模型
产品
解决方案
定价
更多

使用matplotlib绘制specgram时自定义figsize触发内存不足错误

问题场景
  • 使用matplotlib绘制自定义宽高的specgram频谱图时,运行指定代码抛出内存相关报错。
  • 移除自定义宽高的设置后,代码可正常运行,但生成的频谱图尺寸为515x389,不符合自定义尺寸的需求。
触发报错的代码
filename = path
x, sr = librosa.load(filename, mono=True)
widthHeight = (432, 288)
plt.figure(figsize=widthHeight)
plt.specgram(x, NFFT=2048, Fs=2, Fc=0, noverlap=128, cmap='inferno', sides='default', mode='default', scale='dB')
plt.axis('off')
plt.savefig("spec.png", bbox_inches='tight', transparent=True)
plt.clf()
抛出的错误信息
_tkinter.TclError: not enough free memory for image buffer
问题根因

matplotlib 的 figsize 参数单位为英寸,并非像素。按照默认100dpi的渲染密度计算,传入的 (432, 288) 会被解析为432英寸宽、288英寸高的画布,渲染生成的图像像素量达到亿级,远超系统可用内存上限,直接触发Tk图形接口的内存不足报错。
移除自定义宽高时,matplotlib 会加载系统默认的画布尺寸,经 bbox_inches='tight' 裁剪后得到尺寸为515x389的输出文件,与正常运行的表现匹配。

修正方案
  • 按目标像素值换算对应英寸的figsize参数:如果需要最终输出432*288像素的图,以保存时100dpi的默认渲染密度计算,对应的figsize应为 (4.32, 2.88),与传入的像素目标严格匹配。
  • 脚本开头显式指定无交互的渲染后端,避免Tk图形接口申请超大内存缓冲区:
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    
  • 保存图像时可配合pad_inches=0参数,避免自动裁剪导致尺寸偏移,修正后的核心代码片段为:
    plt.figure(figsize=(4.32, 2.88), dpi=100)
    plt.specgram(x, NFFT=2048, Fs=2, Fc=0, noverlap=128, cmap='inferno', sides='default', mode='default', scale='dB')
    plt.axis('off')
    plt.savefig("spec.png", bbox_inches='tight', transparent=True, pad_inches=0)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 14:54:04