3次元ボクセルデータの Python 実現ガイド
【概要】
本ページでは、The Stanford Volume Data Archive が公開するCTスキャンデータ「CThead」を例に、3次元ボクセルデータをPythonで扱う方法を説明する。断層表示と3D等値面表示による可視化、および畳み込み・勾配・補間・平滑化の処理を、NumPy・SciPy・scikit-image・Matplotlibで実装する。
【目次】
【関連する外部ページ】
- Pythonの公式サイト: https://www.python.org
- 東京大学の「Pythonプログラミング入門」: https://utokyo-ipp.github.io/IPP_textbook.pdf
- The Stanford Volume Data Archive: https://graphics.stanford.edu/data/voldata/
【サイト内の関連情報】
- Windows AI支援Python開発環境構築ガイド: 別ページ »で説明
- AIエディタ Windsurf の活用: 別ページ »で説明
- AIエディタCursorガイド: 別ページ »で説明
- Google Colaboratory: 別ページ »で説明
- Python のまとめ: 別ページ »で説明
- 機械学習の Python 実現ガイド: 別ページ »で説明
- 行列計算の Python 実現ガイド: 別ページ »で説明
- 統計分析のPython での実現ガイド: 別ページ »で説明
- 音声信号処理の Python 実現ガイド: 別ページ »で説明
- カラー画像処理の Python 実現ガイド: 別ページ »で説明
- Pythonによる簡単なアドベンチャーゲーム(変数,式,if,while,関数,print,time.sleep, def, global を使用): 別ページ »で説明
- Pythonプログラミング講座:基礎から応用まで(授業資料,全15回): 別ページ »で説明
- Pythonプログラミングの例と実践ガイド: 別ページ »で説明
第1章 3次元ボクセルデータの可視化
1.1 データセットの選定
ボクセル(voxel)とは、2次元画像のピクセル(pixel)を3次元に拡張した概念で、3次元空間を格子状に分割したときの最小単位である。本章では、コンピュータグラフィックス分野で利用されているベンチマークデータを使う。
使用するデータは、The Stanford Volume Data Archive が公開している「CT Study of a Female Cadaver Head」(通称 CThead)である。人体頭部のCTスキャンデータで、医用画像処理やボリュームレンダリング(3次元データを直接画像化する手法)の研究で使われている。
データの仕様
| 項目 | 内容 |
|---|---|
| データ名 | CT Study of a Female Cadaver Head ("CThead") |
| 公開元 | https://graphics.stanford.edu/data/voldata/ |
| 解像度 | 256 × 256 × 113 voxels |
| データ型 | 16ビット整数(ビッグエンディアン:上位バイトが先頭に格納される形式) |
| 形式 | スライス(断層)ごとのRawバイナリファイル113個を .tar.gz 形式で圧縮 |
1.2 Pythonプログラムの概要
本プログラムは、次の3つの工程を実行する。
工程1:データ取得
Stanfordのサーバーからデータをダウンロードし、メモリ上で展開する。
工程2:データ変換
アーカイブ内のスライス画像をファイル名の番号順に並べ替え、積み重ねて3次元配列(NumPy配列)に変換する。
工程3:可視化
変換したデータを2つの方法で可視化する。
- 断層表示(Slice):スライダで断面位置を変えながら、水平断(Axial)の断面を表示する。
- 3D等値面表示(Isosurface):骨(level=800)と皮膚(level=400)の2つの等値面を同じ空間に重ねて描画する。処理量を減らすため、ボクセルを間引いて表示する。
1.3 実行結果
プログラムを実行すると、2つのウィンドウが表示される。
Figure 1:断層表示(Slice Viewer)
3次元配列を水平断で切り出した画像である。スライダを動かすと、表示するスライス番号が変わる。CTやMRIの診断で医師が見る画像と同じ形式である。
Figure 2:3D等値面(Bone + Skin)
Marching Cubesアルゴリズム(ボクセルデータから等値面のポリゴンメッシュを生成する手法)により、指定した濃淡値を持つ位置をつなぎ合わせ、立体的な面として抽出した結果である。
骨(level=800)は白色で不透明寄り、皮膚(level=400)は肌色で半透明に設定し、同じ3D空間に重ねて表示する。これにより外形と内部構造を同時に観察できる。
回転などの操作を軽くするため、step_size=10(10ボクセルごとに1つをサンプリング)で生成している。そのため形状は粗く表示される。
1.4 解説
1.4.1 データ構造
ダウンロードしたデータには、256 × 256ピクセルの断層画像が113枚、個別のファイルとして格納されている。これらを np.stack 関数で積み重ね、(113, 256, 256) の形状の3次元配列を作る。この配列は「高さ・奥行き・幅」を持つ直方体のボリュームデータである。
ファイル名の末尾は連番だが、文字列としてソートするとCThead.1, CThead.10, CThead.100 の順になる。そのため、末尾の数値を整数として取り出してソートする。
1.4.2 可視化の原理
断層表示
3次元の直方体データを特定の平面で切断し、その断面のピクセル値を2次元画像として表示する手法である。
等値面(Isosurface)
等値面は、天気図の等圧線の3次元版に相当する。等圧線が同じ気圧の地点を線で結んだものであるのに対し、等値面は同じ濃淡値の地点を面でつないだものである。
例えば「濃淡値が800の場所」をすべてつなぐと、骨の形状が立体として得られる。ただしそのままではポリゴン数が多く、回転などの操作が重くなる。そのためデータを間引いてポリゴン数を減らす。
複数等値面の同時表示
しきい値を変えると、異なる組織を抽出できる。骨は高い濃淡値(約800)、皮膚や軟部組織は低い濃淡値(約400)を持つ。これらを別々の色と透明度で同じ空間に描画すると、外形と内部構造の位置関係を確認できる。
1.5 Pythonコード
実行前に、コマンドプロンプトで次を実行し、必要なパッケージをインストールする。
pip install numpy scipy scikit-image matplotlib requests
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure
import requests
import tarfile
import io
import re
# ==========================================
# 1. Data Loading
# ==========================================
url = "https://graphics.stanford.edu/data/voldata/CThead.tar.gz"
response = requests.get(url)
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tar:
slice_size = 256 * 256 * 2
members = sorted(
[m for m in tar.getmembers() if m.size == slice_size],
key=lambda m: int(re.search(r'(\d+)$', m.name).group())
)
slices = []
for m in members:
f = tar.extractfile(m)
chunk = np.frombuffer(f.read(), dtype='>u2')
slices.append(chunk.reshape((256, 256)))
volume = np.stack(slices, axis=0).astype(np.float32)
# ==========================================
# 2. Visualization
# ==========================================
z, y, x = volume.shape
# --- Figure 1: Interactive Slice Viewer ---
fig1, ax1 = plt.subplots(figsize=(8, 8))
fig1.canvas.manager.set_window_title('Figure 1: Interactive Slice Viewer')
plt.subplots_adjust(bottom=0.15)
img = ax1.imshow(volume[z // 2, :, :], cmap='gray')
ax1.set_title(f'Axial Slice: {z // 2}')
ax1.axis('off')
ax_slider = plt.axes([0.2, 0.05, 0.6, 0.03])
slider = Slider(ax_slider, 'Slice', 0, z - 1, valinit=z // 2, valstep=1)
def update(val):
idx = int(slider.val)
img.set_data(volume[idx, :, :])
ax1.set_title(f'Axial Slice: {idx}')
fig1.canvas.draw_idle()
slider.on_changed(update)
# --- Figure 2: Multiple Isosurfaces ---
fig2 = plt.figure(figsize=(10, 8))
fig2.canvas.manager.set_window_title('Figure 2: Bone + Skin')
ax = fig2.add_subplot(111, projection='3d')
# 骨(白、不透明寄り)
verts_bone, faces_bone, _, _ = measure.marching_cubes(volume, level=800, step_size=10)
mesh_bone = Poly3DCollection(verts_bone[faces_bone], alpha=0.6)
mesh_bone.set_facecolor([0.9, 0.9, 0.9])
ax.add_collection3d(mesh_bone)
# 皮膚(肌色、半透明)
verts_skin, faces_skin, _, _ = measure.marching_cubes(volume, level=400, step_size=10)
mesh_skin = Poly3DCollection(verts_skin[faces_skin], alpha=0.15)
mesh_skin.set_facecolor([0.9, 0.7, 0.6])
ax.add_collection3d(mesh_skin)
ax.set_xlim(0, z)
ax.set_ylim(0, y)
ax.set_zlim(0, x)
ax.set_title("Bone (white) + Skin (transparent)")
plt.show()
第2章 畳み込み(Convolution)
2.1 概要
畳み込みは、カーネル(kernel)と呼ばれる小さな配列を入力データ上で移動させながら、対応する要素同士を掛けて合計する演算である。本プログラムでは 11×11×11 の平均化カーネルを使う。各ボクセルの値を、そのボクセルを中心とする 11×11×11 = 1331個のボクセルの平均値に置き換えるため、画像はぼける。
上段に元画像、下段に畳み込み後の画像を、水平断(Axial)・冠状断(Coronal)・矢状断(Sagittal)の3方向で表示する。
2.2 Pythonコード
実行前に、コマンドプロンプトで次を実行し、必要なパッケージをインストールする。
pip install numpy scipy matplotlib requests
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
import requests
import tarfile
import io
import re
# ==========================================
# 1. Data Loading
# ==========================================
url = "https://graphics.stanford.edu/data/voldata/CThead.tar.gz"
response = requests.get(url)
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tar:
slice_size = 256 * 256 * 2
members = sorted(
[m for m in tar.getmembers() if m.size == slice_size],
key=lambda m: int(re.search(r'(\d+)$', m.name).group())
)
slices = []
for m in members:
f = tar.extractfile(m)
chunk = np.frombuffer(f.read(), dtype='>u2')
slices.append(chunk.reshape((256, 256)))
volume = np.stack(slices, axis=0).astype(np.float32)
# ==========================================
# 2. Convolution (11x11x11 Averaging Kernel)
# ==========================================
kernel = np.ones((11, 11, 11)) / (11 * 11 * 11)
convolved = ndimage.convolve(volume, kernel)
# ==========================================
# 3. Visualization
# ==========================================
z, y, x = volume.shape
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.canvas.manager.set_window_title('Convolution (11x11x11 Averaging)')
axes[0, 0].imshow(volume[z // 2, :, :], cmap='gray')
axes[0, 0].set_title('Original: Axial')
axes[0, 0].axis('off')
axes[0, 1].imshow(volume[:, y // 2, :], cmap='gray', origin='lower')
axes[0, 1].set_title('Original: Coronal')
axes[0, 1].axis('off')
axes[0, 2].imshow(volume[:, :, x // 2], cmap='gray', origin='lower')
axes[0, 2].set_title('Original: Sagittal')
axes[0, 2].axis('off')
axes[1, 0].imshow(convolved[z // 2, :, :], cmap='gray')
axes[1, 0].set_title('Convolved: Axial')
axes[1, 0].axis('off')
axes[1, 1].imshow(convolved[:, y // 2, :], cmap='gray', origin='lower')
axes[1, 1].set_title('Convolved: Coronal')
axes[1, 1].axis('off')
axes[1, 2].imshow(convolved[:, :, x // 2], cmap='gray', origin='lower')
axes[1, 2].set_title('Convolved: Sagittal')
axes[1, 2].axis('off')
plt.tight_layout()
plt.show()
第3章 勾配(Gradient)
3.1 概要
勾配は、各点における濃淡値の変化率を表すベクトルである。3次元データでは、x・y・z各軸方向の偏微分を計算し、その大きさ(magnitude)を求めることで、濃淡値の変化の大きさを画像化できる。
上段に元画像、下段に勾配の大きさを表示する。元画像では組織全体が見えるのに対し、勾配画像では組織の境界が白く表示される。
3.2 Pythonコード
実行前に、コマンドプロンプトで次を実行し、必要なパッケージをインストールする。
pip install numpy matplotlib requests
import numpy as np
import matplotlib.pyplot as plt
import requests
import tarfile
import io
import re
# ==========================================
# 1. Data Loading
# ==========================================
url = "https://graphics.stanford.edu/data/voldata/CThead.tar.gz"
response = requests.get(url)
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tar:
slice_size = 256 * 256 * 2
members = sorted(
[m for m in tar.getmembers() if m.size == slice_size],
key=lambda m: int(re.search(r'(\d+)$', m.name).group())
)
slices = []
for m in members:
f = tar.extractfile(m)
chunk = np.frombuffer(f.read(), dtype='>u2')
slices.append(chunk.reshape((256, 256)))
volume = np.stack(slices, axis=0).astype(np.float32)
# ==========================================
# 2. Gradient Magnitude
# ==========================================
gz, gy, gx = np.gradient(volume)
gradient_mag = np.sqrt(gx**2 + gy**2 + gz**2)
# ==========================================
# 3. Visualization
# ==========================================
z, y, x = volume.shape
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.canvas.manager.set_window_title('Gradient Magnitude')
axes[0, 0].imshow(volume[z // 2, :, :], cmap='gray')
axes[0, 0].set_title('Original: Axial')
axes[0, 0].axis('off')
axes[0, 1].imshow(volume[:, y // 2, :], cmap='gray', origin='lower')
axes[0, 1].set_title('Original: Coronal')
axes[0, 1].axis('off')
axes[0, 2].imshow(volume[:, :, x // 2], cmap='gray', origin='lower')
axes[0, 2].set_title('Original: Sagittal')
axes[0, 2].axis('off')
axes[1, 0].imshow(gradient_mag[z // 2, :, :], cmap='gray')
axes[1, 0].set_title('Gradient: Axial')
axes[1, 0].axis('off')
axes[1, 1].imshow(gradient_mag[:, y // 2, :], cmap='gray', origin='lower')
axes[1, 1].set_title('Gradient: Coronal')
axes[1, 1].axis('off')
axes[1, 2].imshow(gradient_mag[:, :, x // 2], cmap='gray', origin='lower')
axes[1, 2].set_title('Gradient: Sagittal')
axes[1, 2].axis('off')
plt.tight_layout()
plt.show()
第4章 補間(Interpolation)
4.1 概要
補間は、離散的なデータ点の間の値を求め、解像度を変更する処理である。本プログラムでは、データを各軸1/8に縮小した後、元のサイズに拡大する。最近傍補間(order=0)と3次スプライン補間(order=3)の結果を比較する。
上段に元画像、中段に最近傍補間、下段に3次スプライン補間を表示する。最近傍補間ではブロック状の階段が現れ、3次スプライン補間では階段が滑らかになる。
4.2 Pythonコード
実行前に、コマンドプロンプトで次を実行し、必要なパッケージをインストールする。
pip install numpy scipy matplotlib requests
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
import requests
import tarfile
import io
import re
# ==========================================
# 1. Data Loading
# ==========================================
url = "https://graphics.stanford.edu/data/voldata/CThead.tar.gz"
response = requests.get(url)
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tar:
slice_size = 256 * 256 * 2
members = sorted(
[m for m in tar.getmembers() if m.size == slice_size],
key=lambda m: int(re.search(r'(\d+)$', m.name).group())
)
slices = []
for m in members:
f = tar.extractfile(m)
chunk = np.frombuffer(f.read(), dtype='>u2')
slices.append(chunk.reshape((256, 256)))
volume = np.stack(slices, axis=0).astype(np.float32)
# ==========================================
# 2. Interpolation Comparison
# ==========================================
downscaled = ndimage.zoom(volume, 0.125, order=0)
# 元のサイズに戻すための倍率
factors = np.array(volume.shape) / np.array(downscaled.shape)
upscaled_nearest = ndimage.zoom(downscaled, factors, order=0)
upscaled_spline = ndimage.zoom(downscaled, factors, order=3)
# ==========================================
# 3. Visualization
# ==========================================
z, y, x = volume.shape
fig, axes = plt.subplots(3, 3, figsize=(15, 15))
fig.canvas.manager.set_window_title('Interpolation Comparison')
axes[0, 0].imshow(volume[z // 2, :, :], cmap='gray')
axes[0, 0].set_title('Original: Axial')
axes[0, 0].axis('off')
axes[0, 1].imshow(volume[:, y // 2, :], cmap='gray', origin='lower')
axes[0, 1].set_title('Original: Coronal')
axes[0, 1].axis('off')
axes[0, 2].imshow(volume[:, :, x // 2], cmap='gray', origin='lower')
axes[0, 2].set_title('Original: Sagittal')
axes[0, 2].axis('off')
axes[1, 0].imshow(upscaled_nearest[z // 2, :, :], cmap='gray')
axes[1, 0].set_title('Nearest: Axial')
axes[1, 0].axis('off')
axes[1, 1].imshow(upscaled_nearest[:, y // 2, :], cmap='gray', origin='lower')
axes[1, 1].set_title('Nearest: Coronal')
axes[1, 1].axis('off')
axes[1, 2].imshow(upscaled_nearest[:, :, x // 2], cmap='gray', origin='lower')
axes[1, 2].set_title('Nearest: Sagittal')
axes[1, 2].axis('off')
axes[2, 0].imshow(upscaled_spline[z // 2, :, :], cmap='gray')
axes[2, 0].set_title('Cubic Spline: Axial')
axes[2, 0].axis('off')
axes[2, 1].imshow(upscaled_spline[:, y // 2, :], cmap='gray', origin='lower')
axes[2, 1].set_title('Cubic Spline: Coronal')
axes[2, 1].axis('off')
axes[2, 2].imshow(upscaled_spline[:, :, x // 2], cmap='gray', origin='lower')
axes[2, 2].set_title('Cubic Spline: Sagittal')
axes[2, 2].axis('off')
plt.tight_layout()
plt.show()
第5章 平滑化(Smoothing)
5.1 概要
平滑化は、データに含まれるノイズを低減する処理である。ガウシアンフィルタは、正規分布に基づく重み付け平均を計算する。パラメータσが大きいほどぼけが強くなる。本プログラムではσ=10を使う。
上段に元画像、下段に平滑化後の画像を表示する。細かな構造がぼけ、大きな輪郭が残る。
5.2 Pythonコード
実行前に、コマンドプロンプトで次を実行し、必要なパッケージをインストールする。
pip install numpy scipy matplotlib requests
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage
import requests
import tarfile
import io
import re
# ==========================================
# 1. Data Loading
# ==========================================
url = "https://graphics.stanford.edu/data/voldata/CThead.tar.gz"
response = requests.get(url)
with tarfile.open(fileobj=io.BytesIO(response.content), mode="r:gz") as tar:
slice_size = 256 * 256 * 2
members = sorted(
[m for m in tar.getmembers() if m.size == slice_size],
key=lambda m: int(re.search(r'(\d+)$', m.name).group())
)
slices = []
for m in members:
f = tar.extractfile(m)
chunk = np.frombuffer(f.read(), dtype='>u2')
slices.append(chunk.reshape((256, 256)))
volume = np.stack(slices, axis=0).astype(np.float32)
# ==========================================
# 2. Gaussian Smoothing
# ==========================================
sigma = 10
smoothed = ndimage.gaussian_filter(volume, sigma=sigma)
# ==========================================
# 3. Visualization
# ==========================================
z, y, x = volume.shape
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
fig.canvas.manager.set_window_title(f'Gaussian Smoothing (sigma={sigma})')
axes[0, 0].imshow(volume[z // 2, :, :], cmap='gray')
axes[0, 0].set_title('Original: Axial')
axes[0, 0].axis('off')
axes[0, 1].imshow(volume[:, y // 2, :], cmap='gray', origin='lower')
axes[0, 1].set_title('Original: Coronal')
axes[0, 1].axis('off')
axes[0, 2].imshow(volume[:, :, x // 2], cmap='gray', origin='lower')
axes[0, 2].set_title('Original: Sagittal')
axes[0, 2].axis('off')
axes[1, 0].imshow(smoothed[z // 2, :, :], cmap='gray')
axes[1, 0].set_title(f'Smoothed (sigma={sigma}): Axial')
axes[1, 0].axis('off')
axes[1, 1].imshow(smoothed[:, y // 2, :], cmap='gray', origin='lower')
axes[1, 1].set_title(f'Smoothed (sigma={sigma}): Coronal')
axes[1, 1].axis('off')
axes[1, 2].imshow(smoothed[:, :, x // 2], cmap='gray', origin='lower')
axes[1, 2].set_title(f'Smoothed (sigma={sigma}): Sagittal')
axes[1, 2].axis('off')
plt.tight_layout()
plt.show()