You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于DICOM VR自动校验并转换标签值类型(pydicom实现)

解决方案:根据VR自动转换DICOM标签值类型

核心思路是针对不同的Value Representation(VR)类型,定义对应的类型转换规则,在将值写入DICOM数据集前完成类型适配,解决pandas读取CSV时的类型不匹配问题。

步骤1:定义VR类型转换映射

先整理常见VR对应的目标类型,创建转换函数字典:

import pandas as pd
import pydicom
from pydicom.tag import Tag

def convert_to_str(val):
    # 处理空值,避免转换出错
    if pd.isna(val):
        return ""
    return str(val)

def convert_to_int(val):
    if pd.isna(val):
        return 0
    # 兼容字符串格式的数字
    try:
        return int(val)
    except (ValueError, TypeError):
        return 0

# VR到转换函数的映射,可根据需求扩展
VR_CONVERTERS = {
    # 字符串类VR
    "LO": convert_to_str,
    "SH": convert_to_str,
    "PN": convert_to_str,
    "DA": convert_to_str,
    "UI": convert_to_str,
    # 整数类VR
    "US": convert_to_int,
    "IS": convert_to_int,
    "SS": convert_to_int
}

步骤2:修改原代码,添加类型转换逻辑

在创建DataElement之前,根据当前标签的VR获取对应的转换函数,对CSV读取的值做类型转换:

for index, row in tags_df.iterrows():
    ds = pydicom.read_file(row["Label"])
    row_tags = row.drop("Label")
    for col, val in row_tags.items():
        try:
            tag = Tag(col)
        except:
            print(f"{col} 不是合法标签")
            exit(-1)
        
        vr = dictionary_VR(tag)
        print(f"{tag} {col} : {vr} with {val} 原始类型 {type(val)}")
        
        # 获取对应转换函数,默认转字符串
        converter = VR_CONVERTERS.get(vr, convert_to_str)
        converted_val = converter(val)
        
        ds.add(pydicom.DataElement(tag, vr, converted_val))

关键说明

  • 对于DA(日期)这类VR,必须是字符串格式(如"20231110"),把pandas读成整数的日期值转成字符串即可消除警告。
  • 对于US(无符号短整数)这类需要数值类型的VR,确保值被转换成整数,同时兼容CSV中可能以字符串存储的数字。
  • 可以根据实际使用的VR类型,继续扩展VR_CONVERTERS字典,比如添加浮点数类型的VR(如FL、FD)对应的转换函数。
  • 加入了空值处理,避免CSV中缺失值导致的转换错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:00:21