---
title: M3D-Cap
canonical_url: "https://www.modelscope.cn/datasets/GoodBaiBai88/M3D-Cap"
md_url: "https://www.modelscope.cn/datasets/GoodBaiBai88/M3D-Cap.md"
repository: GoodBaiBai88/M3D-Cap
chinese_name: "3D多模态医疗数据集-图文对"
last_updated: 2024-06-11
license: "Apache License 2.0"
storage_size: "993 GB"
domain:
  - languages
  - multilinguality
  - image-captioning
tasks:
  - en
  - monolingual
  - size_scale
downloads: 261297
stars: 40
---

# M3D-Cap

> M3D-Cap - GoodBaiBai88 在 ModelScope 开源的数据集。大规模 3D 医疗多模态数据集-图文对数据集 (M3D-Caption)

GoodBaiBai88/M3D-Cap 是 ModelScope 魔搭社区上的en、monolingual、size_scale数据集，涉及 languages、multilinguality、image-captioning 领域，存储大小 993 GB，采用 Apache License 2.0 许可。

- **Repository**: GoodBaiBai88/M3D-Cap
- **License**: Apache License 2.0
- **Tasks**: en, monolingual, size_scale
- **Domain**: languages, multilinguality, image-captioning
- **Storage size**: 993 GB
- **Downloads**: 261297
- **Stars**: 40
- **Last updated**: 2024-06-11

Source: https://www.modelscope.cn/datasets/GoodBaiBai88/M3D-Cap

---

## 数据集描述
大规模 3D 医疗多模态数据集-图文对数据集 (M3D-Cap)

### 数据集简介
医疗机构，例如医院，积累了大量的医学图像和诊断报告等多模态数据。
然而，由于涉及患者数据的敏感性和隐私问题，公开这些多模态数据集面临挑战。
为了规避这些限制，我们从公开可访问的专业医学网站 [Radiopaedia](https://radiopaedia.org/) 收集医学图像和报告。
具体来说，我们数据集中的每个患者病例都包括多个 3D 图像以及对应的报告，这些报告经过 Radiopaedia 平台专家的仔细审查。由于 3D CT 在医学图像分析中的关键作用，尤其是在全身病变的诊断、定位和测量方面，
我们将重点放在 3D CT 数据上，并成功构建了一个最大规模的 3D 医学图像-文本配对数据集，名为 M3D-Cap，包括 120K 对图文数据。
数据集总体分为两个文件夹，分别命名为 ct_case 和 ct_quizze 。ct_quizze 用于医学考试，其质量更高。
每个文件夹内包含图像文件夹和文本文件，图像文件夹包含 3D 图像的多个 2D 切片，
文本文件提供了对应 3D 图像的英文报告描述，包括异常类型、病灶位置等。

- **M3D_Cap.json**: 提供了数据集划分方案。
- **data_examples**: 提供了 24 组 3D 图像和文本的数据示例。
- **M3D_Cap**: 提供了完整的数据集，请下载此文件夹。
- **m3d_cap_data_prepare.py**: 提供了数据预处理代码，包括图像归一化、2D 切片合成3D图像，图像裁剪，有效文本提取等。

基于 M3D-Cap 图文对数据集，我们创建了 M3D-VQA 视觉问答数据集，请参考[链接](https://www.modelscope.cn/datasets/GoodBaiBai88/M3D-VQA).


### 数据集支持的任务
M3D-Cap 支持图文检索、报告生成、图像生成等 3D 医疗场景的图文多模态任务。


## 数据集的格式和结构

### 数据格式
<pre>
    M3D_Cap/
        ct_case/
            000006/
                Axial_non_contrast/
                    0.jpeg
                    1.jpeg
                    ......
                text.txt
            ......
        ct_quizze/
            000007/
                Axial_non_contrast/
                    0.png
                    1.png
                    ......
                text.txt
            ......
        ......
</pre>

### 数据集下载
数据集整体大小约为 **978G**。请注意，data_examples 文件夹中的内容仅为示例数据，无需下载。完整的数据集位于 M3D_Cap 文件夹中。

#### Clone with HTTP
:modelscope-code[]{type="git"}

#### SDK下载
:modelscope-code[]{type="sdk"}

#### 手动下载
从数据集文件手动下载所有文件，建议采用批量下载工具。


### 数据集加载方式
#### 1. 预处理
根据 m3d_cap_data_prepare.py 对数据集进行预处理，包括：将数据集中每个文件夹下的 2D 切片组成 3D 图像，并以图像文件名命名（保留平面方向和期相等信息），保存为 `npy` 文件，图像归一化和裁剪等，将数据集中的文本报告进行筛选和提取，获取高质量描述。

#### 2. 构建 Dataset 
我们提供了构建 Dataset 示例代码，
```python
class CapDataset(Dataset):
    def __init__(self, args, tokenizer, mode="train"):
        self.args = args
        self.data_root = args.data_root
        self.tokenizer = tokenizer
        self.mode = mode

        self.image_tokens = "<im_patch>" * args.proj_out_num

        with open(args.cap_data_path, 'r') as file:
            self.json_file = json.load(file)
        self.data_list = self.json_file[mode]

        self.caption_prompts = [
            "Can you provide a caption consists of findings for this medical image?",
            "Describe the findings of the medical image you see.",
            "Please caption this medical scan with findings.",
            "What is the findings of this image?",
            "Describe this medical scan with findings.",
            "Please write a caption consists of findings for this image.",
            "Can you summarize with findings the images presented?",
            "Please caption this scan with findings.",
            "Please provide a caption consists of findings for this medical image.",
            "Can you provide a summary consists of findings of this radiograph?",
            "What are the findings presented in this medical scan?",
            "Please write a caption consists of findings for this scan.",
            "Can you provide a description consists of findings of this medical scan?",
            "Please caption this medical scan with findings.",
            "Can you provide a caption consists of findings for this medical scan?"
        ]

        train_transform = mtf.Compose(
            [
                mtf.RandRotate90(prob=0.5, spatial_axes=(1, 2)),
                mtf.RandFlip(prob=0.10, spatial_axis=0),
                mtf.RandFlip(prob=0.10, spatial_axis=1),
                mtf.RandFlip(prob=0.10, spatial_axis=2),
                mtf.RandScaleIntensity(factors=0.1, prob=0.5),
                mtf.RandShiftIntensity(offsets=0.1, prob=0.5),

                mtf.ToTensor(dtype=torch.float),
            ]
        )

        val_transform = mtf.Compose(
                [
                    mtf.ToTensor(dtype=torch.float),
                ]
            )
        set_track_meta(False)

        if mode == 'train':
            self.transform = train_transform
        elif mode == 'validation':
            self.transform = val_transform
        elif mode == 'test':
            self.transform = val_transform

    def __len__(self):
        return len(self.data_list)

    def __getitem__(self, idx):
        max_attempts = 100
        for _ in range(max_attempts):
            try:
                data = self.data_list[idx]
                image_path = data["image"]
                image_abs_path = os.path.join(self.data_root, image_path)
                image = np.load(image_abs_path)  # nomalized 0-1, C,D,H,W
                image = self.transform(image)

                text_path = data["text"]
                text_abs_path = os.path.join(self.data_root, text_path)
                with open(text_abs_path, 'r') as text_file:
                    raw_text = text_file.read()
                answer = raw_text

                prompt_question = random.choice(self.caption_prompts)

                question = self.image_tokens + prompt_question

                text_tensor = self.tokenizer(
                    question + ' ' + answer, max_length=self.args.max_length, truncation=True, padding="max_length", return_tensors="pt"
                )

                input_id = text_tensor["input_ids"][0]
                attention_mask = text_tensor["attention_mask"][0]

                valid_len = torch.sum(attention_mask)
                if valid_len < len(input_id):
                    input_id[valid_len] = self.tokenizer.eos_token_id

                question_tensor = self.tokenizer(
                    question, max_length=self.args.max_length, truncation=True, padding="max_length", return_tensors="pt"
                )
                question_len = torch.sum(question_tensor["attention_mask"][0])

                label = input_id.clone()
                label[label == self.tokenizer.pad_token_id] = -100
                label[:question_len] = -100

                ret = {
                    'image': image,
                    'input_id': input_id,
                    'label': label,
                    'attention_mask': attention_mask,
                    'question': question,
                    'answer': answer,
                    'question_type': "Caption",
                }
                return ret

            except Exception as e:
                print(f"Error in __getitem__ at index {idx}: {e}")
                idx = random.randint(0, len(self.data_list) - 1)

```

### 数据集划分
整个数据集通过 JSON 文件进行划分，可以被分为`train, validation, test100, test500, test1k, test`，其中 test 包含 2k 个样本。
考虑到测试成本，我们提供了不同数量的测试样本，分别为 100、500、1k 和 2k 的测试集。

## 数据集版权信息
本数据集涉及的所有图像和报告均为公开数据，详细版权信息请参考对应链接。

## 引用方式
如果使用本数据集，需引用以下工作：
```BibTeX
@misc{bai2024m3d,
      title={M3D: Advancing 3D Medical Image Analysis with Multi-Modal Large Language Models}, 
      author={Fan Bai and Yuxin Du and Tiejun Huang and Max Q. -H. Meng and Bo Zhao},
      year={2024},
      eprint={2404.00578},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}
@misc{du2024segvol,
      title={SegVol: Universal and Interactive Volumetric Medical Image Segmentation}, 
      author={Yuxin Du and Fan Bai and Tiejun Huang and Bo Zhao},
      year={2024},
      eprint={2311.13385},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}
```
