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

如何从CSV读取医学图像标签并批量加入TensorFlow数据集?

批量加载DCM图像与对应标签到TensorFlow数据集

你可以通过以下两种方式将CSV中的标签与DCM图像配对,构建包含图像和对应标签的TensorFlow数据集:

方法一:结合Pandas读取CSV(适合中小规模数据集)

先通过Pandas读取CSV提取路径和标签,再创建路径-标签对的数据集,最后修改处理函数同时返回图像和标签:

import tensorflow as tf
import tensorflow_io as tfio
import pandas as pd

# 读取CSV标签文件
df = pd.read_csv("你的标签文件路径.csv")
image_paths = df["image_path"].values
labels = df["image_labels"].values

def process_data(filename, label):
    # DCM图像预处理逻辑
    image_bytes = tf.io.read_file(filename)
    image = tf.squeeze(
        tfio.image.decode_dicom_image(image_bytes, on_error='strict', dtype=tf.uint16),
        axis=0
    )
    # 处理MONOCHROME1类型图像
    photometric_interpretation = tfio.image.decode_dicom_data(
        image_bytes, tfio.image.dicom_tags.PhotometricInterpretation
    )
    image = (image - tf.reduce_min(image)) / (tf.reduce_max(image) - tf.reduce_min(image))
    if photometric_interpretation == "MONOCHROME1":
        image = 1 - image
    image = image * 255
    image = tf.cast(tf.image.resize(image, (512, 512)), tf.uint8)
    # 返回预处理后的图像和对应标签
    return image, label

# 创建路径-标签对的数据集
dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))
# 并行预处理+批量
dataset = dataset.map(process_data, num_parallel_calls=tf.data.AUTOTUNE).batch(50)

方法二:TensorFlow原生CSV读取(适合大规模数据集,流式加载)

如果CSV文件过大,用TensorFlow的TextLineDataset流式读取,避免一次性加载全部数据到内存:

import tensorflow as tf
import tensorflow_io as tfio

def parse_csv_line(line):
    # 定义CSV列的默认类型:image_path为字符串,image_labels为整数
    column_defaults = [tf.string, tf.int32]
    image_path, label = tf.io.decode_csv(line, column_defaults)
    return image_path, label

def process_data(filename, label):
    # 同方法一中的图像预处理逻辑
    image_bytes = tf.io.read_file(filename)
    image = tf.squeeze(
        tfio.image.decode_dicom_image(image_bytes, on_error='strict', dtype=tf.uint16),
        axis=0
    )
    photometric_interpretation = tfio.image.decode_dicom_data(
        image_bytes, tfio.image.dicom_tags.PhotometricInterpretation
    )
    image = (image - tf.reduce_min(image)) / (tf.reduce_max(image) - tf.reduce_min(image))
    if photometric_interpretation == "MONOCHROME1":
        image = 1 - image
    image = image * 255
    image = tf.cast(tf.image.resize(image, (512, 512)), tf.uint8)
    return image, label

# 读取CSV文件,跳过表头行
csv_dataset = tf.data.TextLineDataset("你的标签文件路径.csv").skip(1)
# 解析每一行CSV数据
csv_dataset = csv_dataset.map(parse_csv_line, num_parallel_calls=tf.data.AUTOTUNE)
# 处理图像并配对标签
dataset = csv_dataset.map(process_data, num_parallel_calls=tf.data.AUTOTUNE).batch(50)

验证数据集配对正确性

你可以取出一批数据验证图像与标签是否正确对应:

for images, batch_labels in dataset.take(1):
    print(f"图像批量形状: {images.shape}")
    print(f"对应标签批量: {batch_labels.numpy()}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:25:23