Esempio n. 1
0
    def __init__(self,
                 case_num,
                 transform=None,
                 target_transform=None):  # root表示图片路径
        volume = []
        segmentation = []
        if case_num == -1:  # 如果等于-1,将所有数据集都读入
            volume = []
            segmentation = []
            for i in range(210):
                tmp_volume, tmp_segmentation = load_case(i)
                np.vstack((volume, tmp_volume))
                np.vstack((segmentation, tmp_segmentation))
        elif case_num < 210:
            volume, segmentation = load_case(case_num)
            kid_seg_ims = get_kid_img(segmentation.get_data())  # 取出肾脏分割图
        else:
            volume = load_volume(case_num)

        vol_ims = normalize(volume.get_data(), DEFAULT_HU_MAX,
                            DEFAULT_HU_MIN)  # 将原图归一化转为灰度图
        imgs = []
        if case_num == -1:
            for num in range(vol_ims.shape[0]):
                imgs.append([vol_ims[num], kid_seg_ims[num]])
        elif case_num < 210:
            for num in range(vol_ims.shape[0]):
                # if not np.all(kid_seg_ims[num]==0):
                imgs.append([vol_ims[num], kid_seg_ims[num]])
        else:
            for num in range(vol_ims.shape[0]):
                imgs.append([vol_ims[num], None])
        self.imgs = imgs
        self.transform = transform
        self.target_transform = target_transform
Esempio n. 2
0
def visualize_case(case_num, save=None):
    def minMax(array):
        return (array - np.min(array)) / (np.max(array) - np.min(array))

    volume, segmentation = load_case(case_num)
    X = preprocess_X(volume)
    y = segmentation.get_fdata()
    model = tf.keras.models.load_model(r'MODEL.h5',
                                       custom_objects={
                                           'dice_coef_loss': dice_coef_loss,
                                           'dice_coef': dice_coef
                                       })

    segmentation_pred = model.predict(X)
    kidney = cv2.threshold(segmentation_pred[:, :, :, 1], 0.2, 1,
                           cv2.THRESH_BINARY)[1]
    cancer = cv2.threshold(segmentation_pred[:, :, :, 2], 0.06, 1,
                           cv2.THRESH_BINARY)[1]
    seg_img = np.clip((kidney * 0.5 + cancer), 0, 1)

    cube_show_slider(cube=X[:, :, :, 0],
                     cube1=y,
                     cube2=seg_img,
                     axis=0,
                     cmap='gray')
    if save:
        nifty_img = nib.Nifti1Image(seg_img, volume.affine, volume.header)
        nib.save(nifty_img, "predict\case{}".format(case_num))
Esempio n. 3
0
def load_imgs(case_list=[0],
              height=512,
              width=512,
              channels=1,
              num_class=2,
              no_negative=False,
              normalization=False,
              kidney_only=True):
    for i in case_list:
        volume, segmentation = load_case(i)
        img = volume.get_data()
        # print(img.shape)
        img = to_gray(img, -512, 512).astype(np.uint8)
        seg = segmentation.get_data().astype(np.uint8)
        if normalization: img = (img - np.mean(img)) / np.std(img)  #是否归一化
        img = np.expand_dims(img, axis=-1)
        # print(img.shape)
        mask = seg_to_mask(seg, kidney_only)
        label = np.array([np.max(mask[i]) for i in range(mask.shape[0])
                          ]).astype(np.uint8)  #判断是否有分割内容
        #  np.amax(mask[i],axis=(0,1))[1]		#肾和肿瘤都训练时,选出包含两种内容的图片
        if no_negative:  #不加载不含分割图的
            l = np.squeeze(np.argwhere(label == 1)).tolist()  # positve_list
            img, mask, label = img[l], mask[l], label[l]

        if i == case_list[0]: imgs, masks, labels = img, mask, label
        else:
            imgs = np.concatenate([imgs, img], axis=0)
            masks = np.concatenate([masks, mask], axis=0)
            labels = np.concatenate([labels, label], axis=0)

        print(i, img.shape[0], np.mean(label))

    print('all images', imgs.shape[0], np.mean(labels))
    return imgs, masks, labels
Esempio n. 4
0
def visualize(cid,
              destination,
              hu_min=DEFAULT_HU_MIN,
              hu_max=DEFAULT_HU_MAX,
              k_color=DEFAULT_KIDNEY_COLOR,
              t_color=DEFAULT_TUMOR_COLOR,
              alpha=DEFAULT_OVERLAY_ALPHA):
    # Prepare output location
    out_path = Path(destination)
    if not out_path.exists():
        out_path.mkdir()

    # Load segmentation and volume
    vol, seg = load_case(cid)
    vol = vol.get_data()
    seg = seg.get_data()
    seg = seg.astype(np.int32)

    # Convert to a visual format
    vol_ims = hu_to_grayscale(vol, hu_min, hu_max)
    seg_ims = class_to_color(seg, k_color, t_color)

    # Overlay the segmentation colors
    viz_ims = overlay(vol_ims, seg_ims, seg, alpha)

    # Save individual images to disk
    for i in range(viz_ims.shape[0]):
        fpath = out_path / ("{:05d}.png".format(i))
        scipy.misc.imsave(str(fpath), viz_ims[i])
Esempio n. 5
0
def main():
    img, seg = load_case("123")
    img = img.get_data()
    seg = seg.get_data()
    seg[seg == 1] = 255
    model = pkl.load(open("model.p", "rb"))
    infer_images(img, seg, model)
Esempio n. 6
0
def validationGenerator(case_nums, batch_size):
    #takes data from begining of data set to
    while True:
        for case_num in case_nums:
            volume, segmentation = load_case(case_num)
            X_file = preprocess_X(volume)
            y_file, begining_num, end_num = preprocess_y(segmentation)
            X_file = X_file[begining_num:end_num + 1, :, :]
            y_file = y_file[begining_num:end_num + 1, :, :]
            L = X_file.shape[0]
            batch_start = 0
            batch_end = batch_size
            print('Validation in progress: {:.2f}%'.format(
                ((case_num - np.min(case_nums)) /
                 (np.max(case_nums) - np.min(case_nums))) * 100))
            while batch_start < L:
                limit = min(batch_end, L)
                X = X_file[batch_start:limit, :, :, :]
                y = y_file[batch_start:limit, :, :, :]

                #needs to yield (X, y, [None]) for some reason

                yield (tf.cast(X, dtype=tf.float16),
                       tf.cast(y, dtype=tf.float16), [None])
                batch_start += batch_size
                batch_end += batch_size

            if case_num == case_nums[-1]:
                # breaks loop so it starts again infinietly
                break


# def validationGenerator(case_nums, batch_size):
#     #generates random index from given dataset (validation data is given)
#     while True:
#         random_val_index = case_nums[np.random.randint(0, len(case_nums))]

#         volume, segmentation = load_case(random_val_index)
#         #preprocessing input
#         X_file = preprocess_X(volume)
#         y_file = preprocess_y(segmentation)

#         L = X_file.shape[0]
#         batch_start = 0
#         batch_end = batch_size
#         print('validation in progress please wait')
#         while batch_start < L:
#             limit = min(batch_end, L)
#             X = X_file[batch_start:limit, :, :, :]
#             y = y_file[batch_start:limit, :, :, :]

#             #needs to yield (X, y, [None]) for some reason
#             yield (X.astype(np.float32), y.astype(np.float32))
#             batch_start += batch_size
#             batch_end += batch_size
Esempio n. 7
0
def get_vol_seg_ims(cid,
                    hu_min=DEFAULT_HU_MIN,
                    hu_max=DEFAULT_HU_MAX,
                    k_color=DEFAULT_KIDNEY_COLOR,
                    t_color=DEFAULT_TUMOR_COLOR):
    # Load segmentation and volume
    vol, seg = load_case(cid)
    spacing = vol.affine
    vol = vol.get_data()
    seg = seg.get_data()
    seg = seg.astype(np.int32)

    # Convert to a visual format
    vol_ims = hu_to_grayscale(vol, hu_min, hu_max)
    seg_ims = class_to_color(seg, k_color, t_color)
    return vol, seg, vol_ims, seg_ims
def main():

    vol, seg = load_case('123')
    vol = vol.get_data()
    seg = seg.get_data()

    ball = morphology.disk(2)
    disk = morphology.disk(7)
    jaccards = []
    listImage = []
    listSeg = []
    with imageio.get_writer(os.path.join('kidney1.gif'), mode='I') as writer:
        for i in range(len(vol)):
            seg[i][seg[i] == 1] = 255
            seg[i][seg[i] == 2] = 255
            vol[i] = vol[i] + 2048
            vol[i] = vol[i] / 4096
            vol[i] = 255 * vol[i]
            vol[i][200:400, 100:400] = exposure.equalize_hist(vol[i][200:400,
                                                                     100:400])

            vol[i][200:400, 100:400] = filters.median(vol[i][200:400, 100:400])

            # denoised = filters.rank.median(vol[i][200:400,100:400], ball)

            # markers = filters.rank.gradient(denoised, disk) < 10
            # markers = ndi.label(markers)[0]
            # gradient = filters.rank.gradient(denoised, ball)

            # vol[i][200:400,100:400] = morphology.watershed(gradient, markers)
            listImage.append(vol[i][200:400, 100:400])
            listSeg.append(seg[i][200:400, 100:400])
            # writer.append_data(vol[i][200:400,100:400])

    print(len(listImage), len(listSeg))
    X_train, X_test, y_train, y_test = create_training_dataset(
        listImage, listSeg)
    model = train_model(X_train, y_train, "RF")
    test_model(X_test, y_test, model)
    pkl.dump(model, open("model.p", "wb"))
Esempio n. 9
0
def trainGenerator(case_nums, batch_size):
    #takes data from begining of data set to
    while True:
        for case_num in case_nums:
            volume, segmentation = load_case(case_num)
            #preprocessing input
            X_file = preprocess_X(volume)
            y_file, begining_num, end_num = preprocess_y(segmentation)
            X_file = X_file[begining_num:end_num + 1, :, :]
            y_file = y_file[begining_num:end_num + 1, :, :]
            L = X_file.shape[0]
            batch_start = 0
            batch_end = batch_size
            while batch_start < L:
                limit = min(batch_end, L)
                X = X_file[batch_start:limit, :, :, :]
                y = y_file[batch_start:limit, :, :, :]
                yield (tf.cast(X, dtype=tf.float16),
                       tf.cast(y, dtype=tf.float16), [None])
                batch_start += batch_size
                batch_end += batch_size

            if case_num == case_nums[-1]:
                break
from skimage import segmentation 
from skimage.morphology import disk
from skimage.morphology import binary_closing
from skimage.morphology import binary_dilation
from skimage import restoration
from skimage.segmentation import active_contour
from skimage.filters import gaussian
import matplotlib.pyplot as plt

#instalacja biblioteki do analizy danych z rozszerzeniem .nii
pip install nibabel
!pip install python-utils
from starter_code.utils import load_case

#załadowanie danych i pobranie wycinków
volume0, segmentation0 =load_case("case_00000")
volume0 = volume0.get_fdata() 
segmentation0 = segmentation0.get_fdata()
volume_shape=np.shape(volume0)
segmentation_shape=np.shape(segmentation0)
print(f"shape of volume {volume_shape}")
print(f"shape of segmentation {segmentation_shape}")

#wyswietlenie przekrojów 
#for i in range (0, volume_shape[0],1):
 # plt.figure()
 # plt.imshow(volume0[i],cmap='gray')

#funkcja która umożliwi pracę na wybranych przekrojach z widocznymi nerkami
def show_slices(slices):
   """ Function to display row of image slices """
Esempio n. 11
0
def visualize(cid,
              destination,
              hu_min=DEFAULT_HU_MIN,
              hu_max=DEFAULT_HU_MAX,
              k_color=DEFAULT_KIDNEY_COLOR,
              t_color=DEFAULT_TUMOR_COLOR,
              alpha=DEFAULT_OVERLAY_ALPHA,
              plane=DEFAULT_PLANE):

    plane = plane.lower()

    plane_opts = ["axial", "coronal", "sagittal"]
    if plane not in plane_opts:
        raise ValueError(("Plane \"{}\" not understood. "
                          "Must be one of the following\n\n\t{}\n").format(
                              plane, plane_opts))

    # Prepare output location
    out_path = Path(destination)
    if not out_path.exists():
        out_path.mkdir()

    # Load segmentation and volume
    vol, seg = load_case(cid)
    spacing = vol.affine
    vol = vol.get_data()
    seg = seg.get_data()
    seg = seg.astype(np.int32)

    # Convert to a visual format
    vol_ims = hu_to_grayscale(vol, hu_min, hu_max)
    seg_ims = class_to_color(seg, k_color, t_color)

    # Save individual images to disk
    if plane == plane_opts[0]:
        # Overlay the segmentation colors
        viz_ims = overlay(vol_ims, seg_ims, seg, alpha)
        for i in range(viz_ims.shape[0]):
            fpath = out_path / ("{:05d}.png".format(i))
            imwrite(str(fpath), viz_ims[i])

    if plane == plane_opts[1]:
        # I use sum here to account for both legacy (incorrect) and
        # fixed affine matrices
        spc_ratio = np.abs(np.sum(spacing[2, :])) / np.abs(
            np.sum(spacing[0, :]))
        for i in range(vol_ims.shape[1]):
            fpath = out_path / ("{:05d}.png".format(i))
            vol_im = scipy.misc.imresize(
                vol_ims[:, i, :],
                (int(vol_ims.shape[0] * spc_ratio), int(vol_ims.shape[2])),
                interp="bicubic")
            seg_im = scipy.misc.imresize(
                seg_ims[:, i, :],
                (int(vol_ims.shape[0] * spc_ratio), int(vol_ims.shape[2])),
                interp="nearest")
            sim = scipy.misc.imresize(
                seg[:, i, :],
                (int(vol_ims.shape[0] * spc_ratio), int(vol_ims.shape[2])),
                interp="nearest")
            viz_im = overlay(vol_im, seg_im, sim, alpha)
            imwrite(str(fpath), viz_im)

    if plane == plane_opts[2]:
        # I use sum here to account for both legacy (incorrect) and
        # fixed affine matrices
        spc_ratio = np.abs(np.sum(spacing[2, :])) / np.abs(
            np.sum(spacing[1, :]))
        for i in range(vol_ims.shape[2]):
            fpath = out_path / ("{:05d}.png".format(i))
            vol_im = scipy.misc.imresize(
                vol_ims[:, :, i],
                (int(vol_ims.shape[0] * spc_ratio), int(vol_ims.shape[1])),
                interp="bicubic")
            seg_im = scipy.misc.imresize(
                seg_ims[:, :, i],
                (int(vol_ims.shape[0] * spc_ratio), int(vol_ims.shape[1])),
                interp="nearest")
            sim = scipy.misc.imresize(
                seg[:, :, i],
                (int(vol_ims.shape[0] * spc_ratio), int(vol_ims.shape[1])),
                interp="nearest")
            viz_im = overlay(vol_im, seg_im, sim, alpha)
            imwrite(str(fpath), viz_im)
Esempio n. 12
0
import sys
sys.path.append('/home/kitamiya/Documents/python/snake3D/src')
sys.path.append('/home/kitamiya/Documents/python/snake3D/src/Toolbox')
import Toolbox as tb
from starter_code.utils import load_case
import numpy as np

num = int(sys.argv[1])

volume, segmentation = load_case(num)
img = np.asarray(volume.dataobj)
print(img.shape)

np.save(
    "/home/kitamiya/Documents/python/snake3D/data/numpy/case" + str(num) +
    ".npy", img)
Created on Sun Jun 21 20:45:43 2020

@author: Acer
"""

%cd kits19
from starter_code.utils import load_case
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import metrics

#ładowanie danych treningowych
for i in range(9, 12):
  volume, segmentation = load_case(i)
  vol = volume.get_fdata()
  seg = segmentation.get_fdata()
  
  nsamples, nx, ny = vol.shape
  vol = vol.reshape(nsamples, nx*ny)

  nsamples, nx, ny = seg.shape
  seg = seg.reshape(nsamples, nx*ny)

  if i==9:
    X=vol
    y=seg
  X=np.concatenate((X, vol))
  y=np.concatenate((y, seg))
import sys
sys.path.append('/Users/shomakitamiya/Documents/python/snake3D/src')
sys.path.append('/Users/shomakitamiya/Documents/python/snake3D/src/Toolbox')
import Toolbox as tb
from starter_code.utils import load_case
import numpy as np
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import
import matplotlib.pyplot as plt
from mayavi import mlab

volume, segmentation = load_case(123)
print(type(segmentation))

seg = np.asarray(segmentation.dataobj)
seg = np.where(seg == 1, 1, 0)
seg = seg.astype(np.float32)

# fig = plt.figure()
# ax = fig.gca(projection='3d')
# ax.voxels(seg[100:180,260:340,300:380])
# plt.show()

mlab.clf()
mlab.contour3d(seg[50:250, 200:400, 250:450])
mlab.show()
Esempio n. 15
0
import skimage.transform as trans
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as keras
import skimage.measure as measure
from skimage.transform import resize
from sklearn.model_selection import train_test_split

"""Wczytywanie zdjęć do folderów"""

# Commented out IPython magic to ensure Python compatibility.
for i in range(1,10):
#   %cd /content/kits19/visualized
  volume, segemnatation=load_case('case_0000'+str(i))
  
  os.mkdir("masks_0000" +str(i))
  os.mkdir("images_0000"+str(i))
  mask_out_path = Path("/content/kits19/visualized/masks_0000"+str(i))
  image_out_path = Path("/content/kits19/visualized/images_0000"+str(i))
  s=segemnatation.get_fdata()
  v=volume.get_fdata()

  for j in range(s.shape[0]):  
    maskfpath = mask_out_path / ("{:05d}.png".format(j))
    imagefpath = image_out_path / ("{:05d}.png".format(j))
    imwrite(str(maskfpath), s[j,:,:])
    imwrite(str(imagefpath), v[j,:,:])

"""Przygotowywanie danych do trenowania i testów. Zmniejszenie wielkosci obrazów i określenie ilosci wsadowych case-ów."""
Esempio n. 16
0
def ToPNGfunc(Cases):
    cases = np.linspace(2, Cases - 3, Cases - 4, dtype=np.int)

    TRAIN_PATH_CT = Path('E:\TOM\dataPNG\TRAIN\CT')
    TRAIN_PATH_MASK = Path('E:\TOM\dataPNG\TRAIN\MASK')
    TEST_PATH_CT = Path('E:\TOM\dataPNG\TEST\CT')
    TEST_PATH_MASK = Path('E:\TOM\dataPNG\TEST\MASK')
    #    VALID_PATH_CT = Path('E:\TOM\dataPNG\VALID\CT')
    #    VALID_PATH_MASK = Path('E:\TOM\dataPNG\VALID\MASK')
    a = 0
    b = 0
    train_n = 0
    test_n = 0
    for id in cases:
        ################################ Ładowanie zbioru treningowego zachowyjąc pewnien % czarnych zdjec
        b = a + b
        volume, segmentation = load_case(id)
        segmentation = segmentation.get_fdata()
        volume = volume.get_fdata()
        (a, y, x) = segmentation.shape

        print(f"loading case for TRAINING: {id} out of {Cases}")
        for index in range(b, a + b, 1):

            if (len(np.unique(segmentation[index - b])) > 1
                    or (random.randint(0, 100)) < 3):

                picture_ct = TRAIN_PATH_CT / '{:05d}.png'.format(index)
                picture_mask = TRAIN_PATH_MASK / '{:05d}.png'.format(index)
                train_n += 1

                plt.imsave(fname=str(picture_ct),
                           arr=volume[index - b],
                           format='png',
                           cmap='gray')
                plt.imsave(fname=str(picture_mask),
                           arr=segmentation[index - b],
                           format='png',
                           cmap='gray')

    ################################ Ładowanie zbioru testowego bez czarnych zdjec
    cases = np.linspace(Cases - 2, Cases, 3, dtype=np.int)
    for id in cases:
        b = a + b
        volume, segmentation = load_case(id)
        segmentation = segmentation.get_fdata()
        volume = volume.get_fdata()
        (a, y, x) = segmentation.shape

        print(f"loading case for TESTING: {id} out of {Cases}")
        for index in range(b, a + b, 1):

            if (len(np.unique(segmentation[index - b])) > 1):

                picture_ct = TEST_PATH_CT / '{:05d}.png'.format(index)
                picture_mask = TEST_PATH_MASK / '{:05d}.png'.format(index)
                test_n += 1

                plt.imsave(fname=str(picture_ct),
                           arr=volume[index - b],
                           format='png',
                           cmap='gray')
                plt.imsave(fname=str(picture_mask),
                           arr=segmentation[index - b],
                           format='png',
                           cmap='gray')

    return train_n, test_n
Esempio n. 17
0
#zmiana working directory na folder zawierajacy zdjecie
import os
os.chdir('/Users/komala/Desktop/TOM_projekt/kits19')

from starter_code.utils import load_case
from starter_code.visualize import visualize

volume, segmentation = load_case("case_00000")
visualize("case_00000", "pictures")
Esempio n. 18
0
import imageio
from starter_code.utils import load_case
import os
for i in range(0, 50, 10):
    print(i)
    with imageio.get_writer(os.path.join(f'allkidneys{i}.gif'),
                            mode='I') as writer:
        vol, seg = load_case(str(i))
        vol = vol.get_data()
        mask = vol
        mask2 = vol
        seg = seg.get_data()
        seg[seg == 1] = 255
        for v in range(len(seg)):
            writer.append_data(seg[v][200:400, 100:400])
Esempio n. 19
0
def visualize(cid,
              destination,
              hu_min=DEFAULT_HU_MIN,
              hu_max=DEFAULT_HU_MAX,
              k_color=DEFAULT_KIDNEY_COLOR,
              t_color=DEFAULT_TUMOR_COLOR,
              alpha=DEFAULT_OVERLAY_ALPHA,
              plane=DEFAULT_PLANE,
              less_ram=False):

    plane = plane.lower()

    plane_opts = ["axial", "coronal", "sagittal"]
    if plane not in plane_opts:
        raise ValueError(("Plane \"{}\" not understood. "
                          "Must be one of the following\n\n\t{}\n").format(
                              plane, plane_opts))

    # Prepare output location
    out_path = Path(destination)
    if not out_path.exists():
        out_path.mkdir()

    # Load segmentation and volume
    vol, seg = load_case(cid)
    spacing = vol.affine
    vol = vol.get_data()
    seg = seg.get_data()
    seg = seg.astype(np.int32)

    vol_ims = None
    seg_ims = None
    if not less_ram:
        # Convert to a visual format
        vol_ims = hu_to_grayscale(vol, hu_min, hu_max).astype(np.uint8)
        seg_ims = class_to_color(seg, k_color, t_color).astype(np.uint8)

    # Save individual images to disk
    if plane == plane_opts[0]:
        if less_ram:
            for j in range(vol.shape[0]):
                vol_ims = hu_to_grayscale(vol[j:j + 1], hu_min, hu_max)
                seg_ims = class_to_color(seg[j:j + 1], k_color, t_color)

                viz_ims = overlay(vol_ims, seg_ims, seg[j:j + 1], alpha)
                for i in range(viz_ims.shape[0]):
                    fpath = out_path / ("{:05d}.png".format(j))
                    imwrite(str(fpath), viz_ims[i])

        else:
            # Overlay the segmentation colors
            viz_ims = overlay(vol_ims, seg_ims, seg, alpha)
            for i in range(viz_ims.shape[0]):
                fpath = out_path / ("{:05d}.png".format(i))
                imwrite(str(fpath), viz_ims[i])

    if plane == plane_opts[1]:
        # I use sum here to account for both legacy (incorrect) and
        # fixed affine matrices
        spc_ratio = np.abs(spacing[2, 0]) / np.abs(spacing[0, 2])

        if less_ram:
            for j in range(vol.shape[1]):
                vol_ims = hu_to_grayscale(vol[:, j:j + 1], hu_min,
                                          hu_max).astype(np.uint8)
                seg_ims = class_to_color(seg[:, j:j + 1], k_color,
                                         t_color).astype(np.uint8)

                for i in range(vol_ims.shape[1]):
                    fpath = out_path / ("{:05d}.png".format(j))
                    vol_im = np.array(
                        Image.fromarray(vol_ims[:, i, :]).resize(
                            (int(vol_ims.shape[2]),
                             int(vol_ims.shape[0] * spc_ratio)),
                            resample=Image.BICUBIC))
                    seg_im = np.array(
                        Image.fromarray(seg_ims[:, i, :]).resize(
                            (int(vol_ims.shape[2]),
                             int(vol_ims.shape[0] * spc_ratio)),
                            resample=Image.NEAREST))
                    sim = np.array(
                        Image.fromarray(seg[:, j, :]).resize(
                            (int(vol_ims.shape[2]),
                             int(vol_ims.shape[0] * spc_ratio)),
                            resample=Image.NEAREST))
                    viz_im = overlay(vol_im, seg_im, sim, alpha)
                    imwrite(str(fpath), viz_im)

        else:
            for i in range(vol_ims.shape[1]):
                fpath = out_path / ("{:05d}.png".format(i))
                vol_im = np.array(
                    Image.fromarray(vol_ims[:, i, :]).resize(
                        (int(vol_ims.shape[2]),
                         int(vol_ims.shape[0] * spc_ratio)),
                        resample=Image.BICUBIC))
                seg_im = np.array(
                    Image.fromarray(seg_ims[:, i, :]).resize(
                        (int(vol_ims.shape[2]),
                         int(vol_ims.shape[0] * spc_ratio)),
                        resample=Image.NEAREST))
                sim = np.array(
                    Image.fromarray(seg[:, i, :]).resize(
                        (int(vol_ims.shape[2]),
                         int(vol_ims.shape[0] * spc_ratio)),
                        resample=Image.NEAREST))
                viz_im = overlay(vol_im, seg_im, sim, alpha)
                imwrite(str(fpath), viz_im)

    if plane == plane_opts[2]:
        # I use sum here to account for both legacy (incorrect) and
        # fixed affine matrices
        spc_ratio = np.abs(spacing[2, 0]) / np.abs(spacing[1, 1])

        if less_ram:
            for j in range(vol.shape[2]):
                vol_ims = hu_to_grayscale(vol[:, :, j:j + 1], hu_min,
                                          hu_max).astype(np.uint8)
                seg_ims = class_to_color(seg[:, :, j:j + 1], k_color,
                                         t_color).astype(np.uint8)

                for i in range(vol_ims.shape[2]):
                    fpath = out_path / ("{:05d}.png".format(j))
                    vol_im = np.array(
                        Image.fromarray(vol_ims[:, :, i]).resize(
                            (int(vol_ims.shape[1]),
                             int(vol_ims.shape[0] * spc_ratio)),
                            resample=Image.BICUBIC))
                    seg_im = np.array(
                        Image.fromarray(seg_ims[:, :, i]).resize(
                            (int(vol_ims.shape[1]),
                             int(vol_ims.shape[0] * spc_ratio)),
                            resample=Image.NEAREST))
                    sim = np.array(
                        Image.fromarray(seg[:, :, j]).resize(
                            (int(vol_ims.shape[1]),
                             int(vol_ims.shape[0] * spc_ratio)),
                            resample=Image.NEAREST))
                    viz_im = overlay(vol_im, seg_im, sim, alpha)
                    imwrite(str(fpath), viz_im)

        else:
            for i in range(vol_ims.shape[2]):
                fpath = out_path / ("{:05d}.png".format(i))
                vol_im = np.array(
                    Image.fromarray(vol_ims[:, :, i]).resize(
                        (int(vol_ims.shape[1]),
                         int(vol_ims.shape[0] * spc_ratio)),
                        resample=Image.BICUBIC))
                seg_im = np.array(
                    Image.fromarray(seg_ims[:, :, i]).resize(
                        (int(vol_ims.shape[1]),
                         int(vol_ims.shape[0] * spc_ratio)),
                        resample=Image.NEAREST))
                sim = np.array(
                    Image.fromarray(seg[:, :, i]).resize(
                        (int(vol_ims.shape[1]),
                         int(vol_ims.shape[0] * spc_ratio)),
                        resample=Image.NEAREST))
                viz_im = overlay(vol_im, seg_im, sim, alpha)
                imwrite(str(fpath), viz_im)