資料集文件

建立 NIfTI 資料集

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

建立 NIfTI 資料集

本頁面展示如何使用 datasets 函式庫建立並共享 NIfTI 格式 (.nii / .nii.gz) 的醫學影像資料集。

您可以透過在 Hugging Face Hub 上建立資料集儲存庫,與您的團隊或社群中的任何人共享資料集。

from datasets import load_dataset

dataset = load_dataset("<username>/my_nifti_dataset")

建立 NIfTI 資料集通常有兩種方式:

  • 在 Python 中從本地 NIfTI 檔案建立資料集,並使用 Dataset.push_to_hub 上傳。
  • 使用基於資料夾的慣例(每個樣本一個檔案)以及一個小型輔助工具將其轉換為 Dataset

您可以要求使用者先分享聯絡資訊來控制資料集的存取權限。欲知更多資訊,請查看 Gated datasets (受限資料集) 指南。

本機檔案

如果您已經有一份 NIfTI 檔案路徑清單,最簡單的工作流程是從該清單建立一個 Dataset,並將欄位轉型 (cast) 為 Nifti 特徵。

from datasets import Dataset
from datasets import Nifti

# simple example: create a dataset from file paths
files = ["/path/to/scan_001.nii.gz", "/path/to/scan_002.nii.gz"]
ds = Dataset.from_dict({"nifti": files}).cast_column("nifti", Nifti())

# access a decoded nibabel image (if decode=True)
# ds[0]["nifti"] will be a nibabel.Nifti1Image object when decode=True
# or a dict {'bytes': None, 'path': '...'} when decode=False

Nifti 特徵支援 decode 參數。當 decode=True(預設值)時,它會將 NIfTI 檔案載入為 nibabel.nifti1.Nifti1Image 物件。您可以使用 img.get_fdata() 以 numpy 陣列形式存取影像資料。當 decode=False 時,它會回傳包含檔案路徑與位元組 (bytes) 的字典。

from datasets import Dataset, Nifti

ds = Dataset.from_dict({"nifti": ["/path/to/scan.nii.gz"]}).cast_column("nifti", Nifti(decode=True))
img = ds[0]["nifti"]  # instance of: nibabel.nifti1.Nifti1Image
arr = img.get_fdata()

準備好資料集後,您可以將其推送至 Hub。

ds.push_to_hub("<username>/my_nifti_dataset")

這將建立一個包含您 NIfTI 資料集的資料集儲存庫,其中包含存放 parquet 分片 (shards) 的 data/ 資料夾。

資料夾慣例與元資料

如果您將資料集組織在資料夾中,可以遵循以下結構自動建立分割(訓練集/測試集/驗證集):

dataset/train/scan_0001.nii
dataset/train/scan_0002.nii
dataset/validation/scan_1001.nii
dataset/test/scan_2001.nii

如果您有標籤或其他元資料,請在資料夾中提供 metadata.csvmetadata.jsonlmetadata.parquet,以便將檔案連結至元資料列。該元資料必須包含一個 file_name(或 *_file_name)欄位,其中記錄了相對於元資料檔案之 NIfTI 檔案的相對路徑。

metadata.csv 範例

file_name,patient_id,age,diagnosis
scan_0001.nii.gz,P001,45,healthy
scan_0002.nii.gz,P002,59,disease_x

Nifti 特徵也適用於壓縮後的資料集——每個 zip 檔皆可包含 NIfTI 檔案與一個元資料檔案。這在以上傳封存檔形式上傳大型資料集時非常有用。這意味著您的資料集結構可能如下(混合了壓縮與未壓縮的檔案):

dataset/train/scan_0001.nii.gz
dataset/train/scan_0002.nii
dataset/validation/scan_1001.nii.gz
dataset/test/scan_2001.nii

轉換為 PyTorch 張量

使用 set_transform() 函式對資料集的批次即時 (on-the-fly) 套用轉換。

import torch 
import nibabel
import numpy as np

def transform_to_pytorch(example):
    example["nifti_torch"] = [torch.tensor(ex.get_fdata()) for ex in example["nifti"]]
    return example

ds.set_transform(transform_to_pytorch)

現在存取元素(例如 ds[0])將會在 "nifti_torch" 鍵中產生 torch 張量。

Nifti1Image 的用法

NIfTI 是一種用於儲存 3 維(甚至 4 維)腦部掃描結果的格式。這包含 3 個空間維度 (x, y, z) 以及選用的時間維度 (t)。此外,此處給定的位置僅相對於掃描儀,因此使用了維度 (4, 5, 6) 來將其提升至真實世界的座標。

您可以利用 matplotlib 將 nifti 檔案視覺化,範例如下:

import matplotlib.pyplot as plt
from datasets import load_dataset

def show_slices(slices):
   """ Function to display row of image slices """
   fig, axes = plt.subplots(1, len(slices))
   for i, slice in enumerate(slices):
       axes[i].imshow(slice.T, cmap="gray", origin="lower")

nifti_ds = load_dataset("<username>/my_nifti_dataset")
for epi_img in nifti_ds:
    nifti_img = epi_img["nifti"].get_fdata()
    show_slices([nifti_img[:, :, 16], nifti_img[26, :, :], nifti_img[:, 30, :]])
    plt.show()

欲進一步閱讀,請參考 nibabel 文件,特別是這個 nibabel 教學

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.