deep-learning-with-pytorch / dlwpt-code

Code for the book Deep Learning with PyTorch by Eli Stevens, Luca Antiga, and Thomas Viehmann.
https://www.manning.com/books/deep-learning-with-pytorch
4.69k stars 1.99k forks source link

CT 3D Visual #32

Closed OverLordGoldDragon closed 3 years ago

OverLordGoldDragon commented 3 years ago

Figured it helpful to interactively dig in skeletons:

Requirement: plotly. Guide.

import os
import glob
import torch
import torch.nn as nn
import numpy as np
import SimpleITK as sitk

import plotly.graph_objs as go
from plotly.offline import plot  # for IDE (e.g. Spyder use)

#%%# Load data ###############################################################
_dir = r"C:\LUNA\\"  # replace with path to your 'subset*' directory
path = glob.glob(os.path.join(_dir, 'subset*\\*.mhd'))[0]

ct_mhd = sitk.ReadImage(path)
ct_a = np.array(sitk.GetArrayFromImage(ct_mhd), dtype=np.float32)
ct_a.clip(-1000, 1000, ct_a)

#%%# Downsample #######
ct_a_t = torch.tensor([[ct_a]])
ctm = nn.MaxPool3d(4)(ct_a_t).numpy()[0][0]

#%%# Prepare to plot ##
a, b, c = ctm.shape
l = 16
X, Y, Z = np.mgrid[-l:l:a*1j, -l:l:b*1j, -l:l:c*1j]

#%%# Plot in browser #########################################################
fig = go.Figure(data=go.Volume(
    x=X.flatten(),
    y=Y.flatten(),
    z=Z.flatten(),
    value=ctm.flatten(),
    opacity=0.15, # small to see through surfaces
    surface_count=12, # larger -> better volume rendering
    colorscale='RdBu',
    ))
plot(fig, auto_open=True)
elistevens commented 3 years ago

Thanks for the contribution! Since this isn't really an issue, per se, I'm going to close this, but I'd like to welcome you to turn it into a gist or a PR for a file in a reader_contributions/ subdir that could hold things like this. Thanks!