You need to enable JavaScript to run this app. 如何保存无白边图像及处理语义分割训练用掩码的标注问题
优惠活动
大模型
产品
解决方案
定价
更多

如何保存无白边图像及处理语义分割训练用掩码的标注问题

语义分割模型训练数据存储问题解决方案

问题1:plt.savefig()保存图像残留细白边框修复

仅设置bbox_inches='tight'无法消除matplotlib默认预留的子图内边距,需配合以下设置完全清除白边:

  • 绘图完成后关闭坐标轴显示:plt.axis('off')
  • 消除所有子图边距:plt.subplots_adjust(left=0, bottom=0, right=1, top=1, hspace=0, wspace=0)
  • 保存时新增pad_inches=0参数,完整保存示例:
plt.savefig('output.png', bbox_inches='tight', pad_inches=0, dpi=300)

如果使用subplots创建画布对象,可将边距设置改为fig.subplots_adjust(left=0, bottom=0, right=1, top=1),效果一致。


问题2:掩码二值标注(白背景标注为0、红色区域标注为1)实现

分为两种场景处理,优先选择生成时直接输出掩码数组的方案,精度更高。

场景1:生成掩码时直接输出二值数组(推荐)

使用plt.fill()绘制时无需先存为图片,可直接将画布渲染结果转为numpy数组后做二值转换:

import numpy as np
import matplotlib.pyplot as plt

# 按你需要的掩码分辨率设置画布尺寸
mask_width = 512
mask_height = 512
fig, ax = plt.subplots(figsize=(mask_width/100, mask_height/100), dpi=100)

# 关闭坐标轴、清空边距
ax.axis('off')
fig.subplots_adjust(left=0, bottom=0, right=1, top=1)

# 绘制轮辙区域,x_coords、y_coords为轮辙轮廓的坐标列表
ax.fill(x_coords, y_coords, color='red')

# 渲染画布为numpy数组
fig.canvas.draw()
mask_arr = np.array(fig.canvas.renderer.buffer_rgba())[:, :, :3]

# 二值转换:红色区域R=255、G=0、B=0,白色区域三通道均为255
binary_mask = ((mask_arr[:, :, 0] == 255) & (mask_arr[:, :, 1] == 0) & (mask_arr[:, :, 2] == 0)).astype(np.uint8)

输出的binary_mask中红色区域值为1,白色背景值为0,可直接保存为npy文件或单通道掩码图使用。

场景2:已保存的掩码图片后处理

如果已批量生成掩码图片,可通过颜色阈值分割实现二值标注,OpenCV实现示例:

import cv2
import numpy as np

# 读入掩码图片,OpenCV默认按BGR格式读取
img = cv2.imread('rut_mask.png')
# 设置红色阈值范围,允许小范围颜色误差
lower_red = np.array([0, 0, 200])
upper_red = np.array([50, 50, 255])
# 提取红色区域并转换为0、1值
binary_mask = cv2.inRange(img, lower_red, upper_red) // 255

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 11:12:03