MONAI 0.7 : tutorials : モジュール – Nifti 読み込み例 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 10/21/2021 (0.7.0)
* 本ページは、MONAI の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- テレワーク & オンライン授業を支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
- ウェビナー運用には弊社製品「ClassCat® Webinar」を利用しています。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション |
E-Mail:sales-info@classcat.com ; WebSite: https://www.classcat.com/ ; Facebook |
MONAI 0.7 : tutorials : モジュール – Nifti 読み込み例
NIfTI ファイルを読みそしてそれらからロードされたボリュームの画像パッチに渡る反復を例示して説明します。
このノートブックの目的は、NIfTI ファイルを読みそしてそれらからロードされたボリュームの画像パッチに渡る反復を例示して説明します。
環境のセットアップ
!python -c "import monai" || pip install -q "monai-weekly[nibabel]"
インポートのセットアップ
# Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import os
import shutil
import tempfile
import nibabel as nib
import numpy as np
import torch
from monai.config import print_config
from monai.data import (
ArrayDataset, GridPatchDataset, create_test_image_3d, PatchIter)
from monai.transforms import (
AddChannel,
Compose,
LoadImage,
RandSpatialCrop,
ScaleIntensity,
EnsureType,
)
from monai.utils import first
print_config()
MONAI version: 0.6.0rc1+23.gc6793fd0 Numpy version: 1.20.3 Pytorch version: 1.9.0a0+c3d40fd MONAI flags: HAS_EXT = True, USE_COMPILED = False MONAI rev id: c6793fd0f316a448778d0047664aaf8c1895fe1c Optional dependencies: Pytorch Ignite version: 0.4.5 Nibabel version: 3.2.1 scikit-image version: 0.15.0 Pillow version: 7.0.0 Tensorboard version: 2.5.0 gdown version: 3.13.0 TorchVision version: 0.10.0a0 ITK version: 5.1.2 tqdm version: 4.53.0 lmdb version: 1.2.1 psutil version: 5.8.0 pandas version: 1.1.4 einops version: 0.3.0 For details about installing the optional dependencies, please visit: https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies
データディレクトリのセットアップ
MONAI_DATA_DIRECTORY 環境変数でディレクトリを指定できます。これは結果をセーブしてダウンロードを再利用することを可能にします。指定されない場合、一時ディレクトリが使用されます。
directory = os.environ.get("MONAI_DATA_DIRECTORY")
root_dir = tempfile.mkdtemp() if directory is None else directory
print(root_dir)
/tmp/tmp3y4h4i5o
幾つかのテスト Nifti ファイルを作成します :
for i in range(5):
im, seg = create_test_image_3d(128, 128, 128)
n = nib.Nifti1Image(im, np.eye(4))
nib.save(n, os.path.join(root_dir, f"im{i}.nii.gz"))
n = nib.Nifti1Image(seg, np.eye(4))
nib.save(n, os.path.join(root_dir, f"seg{i}.nii.gz"))
Ref.
test_file = root_dir + "/im0.nii.gz" img_test = nib.load(test_file) print(type(img_test), img_test.shape) img_ary = img_test.get_fdata()[:, :, 64] print(type(img_ary), img_ary.shape, img_ary.dtype) plt.imshow(img_ary)
<class 'nibabel.nifti1.Nifti1Image'> (128, 128, 128) <class 'numpy.ndarray'> (128, 128) float64
![]()
plt.subplots(4, 3, figsize=(128, 128)) for i in range(12): img_ary = img_test.get_fdata()[:, :, i*10] plt.subplot(4, 3, i + 1) plt.imshow(img_ary, cmap="gray") plt.tight_layout() plt.show()
![]()
ロードされた Nifti ファイルから一様なランダムパッチを生成するデータローダを作成します :
images = sorted(glob.glob(os.path.join(root_dir, "im*.nii.gz")))
segs = sorted(glob.glob(os.path.join(root_dir, "seg*.nii.gz")))
imtrans = Compose(
[
LoadImage(image_only=True),
ScaleIntensity(),
AddChannel(),
RandSpatialCrop((64, 64, 64), random_size=False),
EnsureType(),
]
)
segtrans = Compose(
[
LoadImage(image_only=True),
AddChannel(),
RandSpatialCrop((64, 64, 64), random_size=False),
EnsureType(),
]
)
ds = ArrayDataset(images, imtrans, segs, segtrans)
loader = torch.utils.data.DataLoader(
ds, batch_size=10, num_workers=2, pin_memory=torch.cuda.is_available()
)
im, seg = first(loader)
print(im.shape, seg.shape)
torch.Size([5, 1, 64, 64, 64]) torch.Size([5, 1, 64, 64, 64])
あるいは、ロードされた画像から規則的なグリッド順でパッチを生成するデータローダを作成します :
imtrans = Compose([LoadImage(image_only=True),
ScaleIntensity(), AddChannel(), EnsureType()])
segtrans = Compose([LoadImage(image_only=True), AddChannel(), EnsureType()])
ds = ArrayDataset(images, imtrans, segs, segtrans)
patch_iter = PatchIter(patch_size=(64, 64, 64), start_pos=(0, 0, 0))
def img_seg_iter(x):
return (zip(patch_iter(x[0]), patch_iter(x[1])),)
ds = GridPatchDataset(ds, img_seg_iter, with_coordinates=False)
loader = torch.utils.data.DataLoader(
ds, batch_size=10, num_workers=2, pin_memory=torch.cuda.is_available()
)
im, seg = first(loader)
print("image shapes:", im[0].shape, seg[0].shape)
print("coordinates shapes:", im[1].shape, seg[1].shape)
image shapes: torch.Size([3, 1, 64, 64, 64]) torch.Size([3, 1, 64, 64, 64]) coordinates shapes: torch.Size([3, 4, 2]) torch.Size([3, 4, 2])
データディレクトリのクリーンアップ
一時ディレクトリが使用された場合にはディレクトリを削除します。
if directory is None:
shutil.rmtree(root_dir)
以上