如何用Python将Mask图像转为图像分割任务的Ground Truth
膝关节MRI Mask格式转换(适配图像分割训练)
核心问题分析
你的Mask无法正常训练,大概率是这几个原因:
- 格式错误:RGB格式的Mask(黑底+彩色ROI)不适合分割模型,需要单通道灰度图,且每个类别对应唯一整数(背景=0,目标ROI=1)
- 像素值异常:ROI像素值不是模型预期的类别整数(比如用255代替1),导致Dice系数计算失效
- 尺寸不匹配:Mask与MRI原图尺寸不一致,训练时数据完全错位
Python转换方案
单张Mask转换代码
import cv2 import numpy as np def convert_mask(input_path, output_path): # 以灰度模式读取原始Mask mask = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE) if mask is None: raise ValueError(f"无法读取文件: {input_path}") # 将所有非0的ROI像素设为1,背景保持0(二分类场景) # 多分类场景可根据原ROI像素值映射到对应类别,比如原255→1,127→2 converted_mask = np.where(mask > 0, 1, 0).astype(np.uint8) # 保存转换后的单通道Mask cv2.imwrite(output_path, converted_mask) # 测试单张转换 convert_mask("raw_mask.png", "processed_mask.png")
批量处理文件夹内所有Mask
import os def batch_convert(input_dir, output_dir): os.makedirs(output_dir, exist_ok=True) for fname in os.listdir(input_dir): if fname.lower().endswith((".png", ".jpg", ".jpeg")): in_path = os.path.join(input_dir, fname) out_path = os.path.join(output_dir, fname) try: convert_mask(in_path, out_path) print(f"完成: {fname}") except Exception as e: print(f"失败 {fname}: {str(e)}") # 执行批量转换 batch_convert("./raw_masks", "./processed_masks")
验证转换结果
- 检查通道数:读取转换后的Mask,打印
mask.shape,应为单通道(例如(512, 512)) - 检查像素值:运行
np.unique(mask),确认只有0和1(二分类)或对应类别的整数 - 核对尺寸:确保转换后的Mask和对应MRI图像的宽高完全一致
多分类场景适配
如果你的Mask包含多个膝关节结构(比如股骨、胫骨),先确定每个结构的原始像素值,修改映射规则:
# 示例:原Mask中255对应股骨(类别1),127对应胫骨(类别2),0为背景 converted_mask = np.zeros_like(mask, dtype=np.uint8) converted_mask[mask == 255] = 1 converted_mask[mask == 127] = 2
内容的提问来源于stack exchange,提问作者Wayne Dan
相关产品推荐
相关产品推荐

