如何用Matplotlib保存带圆形裁剪区域的透明无白边图片?
圆形裁剪Matplotlib图片并去除白边的解决方案
需求与问题
需要用Matplotlib将图片裁剪为圆形区域,要求圆形外为透明区域且无白边,但当前实现代码输出存在白边,不符合预期。
原代码:
import matplotlib.pyplot as plt import matplotlib.cbook as cbook import matplotlib.patches as patches with cbook.get_sample_data('grace_hopper.jpg') as image_file: image = plt.imread(image_file) fig, ax = plt.subplots() im = ax.imshow(image) patch = patches.Circle((260, 200), radius=200, transform=ax.transData) im.set_clip_path(patch) ax.axis('off') plt.show()
解决方法
问题根源是画布背景默认不透明、画布包含圆形外冗余区域,且保存时未正确处理透明通道。以下是修正后的完整代码:
import matplotlib.pyplot as plt import matplotlib.cbook as cbook import matplotlib.patches as patches with cbook.get_sample_data('grace_hopper.jpg') as image_file: image = plt.imread(image_file) # 创建画布:尺寸匹配圆形直径(dpi=100时,4英寸对应400像素,适配半径200的圆形) fig, ax = plt.subplots(figsize=(4, 4), dpi=100) fig.patch.set_alpha(0.0) # 设置画布背景完全透明 im = ax.imshow(image) patch = patches.Circle((260, 200), radius=200, transform=ax.transData) im.set_clip_path(patch) # 彻底移除边距与坐标轴占用空间 ax.axis('off') ax.margins(0) fig.subplots_adjust(left=0, right=1, top=1, bottom=0) # 保存时启用透明通道,去除所有冗余空白 plt.savefig('circular_grace.png', format='png', transparent=True, bbox_inches='tight', pad_inches=0) plt.show()
关键改动说明
fig.patch.set_alpha(0.0):将画布背景设为透明,避免圆形外出现白色底色figsize=(4,4):根据圆形尺寸匹配画布大小,减少冗余区域fig.subplots_adjust+ax.margins(0):彻底清除子图边距与坐标轴预留空间plt.savefig参数:transparent=True保留透明通道,bbox_inches='tight'+pad_inches=0确保保存时无多余空白
内容的提问来源于stack exchange,提问作者Niklas




