Skip to content
Snippets Groups Projects
Commit 3d9eefad authored by Julius Steiglechner's avatar Julius Steiglechner
Browse files

Add functionality for single directions.

parent 14bad5a6
No related branches found
No related tags found
No related merge requests found
......@@ -12,6 +12,7 @@ from pathlib import Path
from typing import Union
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize, Colormap
import nibabel as nib
import numpy as np
......@@ -23,7 +24,7 @@ def visualize_image_with_mask(
image: np.ndarray,
mask: np.ndarray,
affine: np.ndarray,
color_map: Colormap = colorblind_friendly_cmap,
color_map: Colormap = cm.hot,
target_path: Union[Path, str] = None,
show_plot: bool = False,
) -> None:
......@@ -33,11 +34,11 @@ def visualize_image_with_mask(
Parameters
----------
image : np.ndarray
DESCRIPTION.
Imag to plot.
mask : np.ndarray
DESCRIPTION.
Discrete mask for overlay.
affine : np.ndarray
DESCRIPTION.
Affine matrix that provides resolution.
target_path : Union[Path, str], optional
Path where to save the plot. The default is None.
show_plot: bool, optional
......@@ -83,7 +84,7 @@ def visualize_image_with_mask(
np.fliplr(np.rot90(mask[ref_pos_x, zoom_y:-(zoom_y+1),
zoom_z:-(zoom_z+1)])),
color_map,
alpha=0.4
alpha=0.7
* np.fliplr(np.rot90((mask[ref_pos_x, zoom_y:-(zoom_y+1),
zoom_z:-(zoom_z+1)] != 0) * 1.)),
**params
......@@ -103,7 +104,7 @@ def visualize_image_with_mask(
np.fliplr(np.rot90(mask[zoom_x:-(zoom_x+1), ref_pos_y,
zoom_z:-(zoom_z+1)])),
color_map,
alpha=0.4
alpha=0.7
* np.fliplr(np.rot90((mask[zoom_x:-(zoom_x+1), ref_pos_y,
zoom_z:-(zoom_z+1)] != 0) * 1.)),
**params
......@@ -123,7 +124,7 @@ def visualize_image_with_mask(
np.fliplr(np.rot90(mask[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1),
ref_pos_z])),
color_map,
alpha=0.4
alpha=0.7
* np.fliplr(np.rot90((mask[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1),
ref_pos_z] != 0) * 1.)),
**params
......@@ -164,7 +165,332 @@ def visualize_prediction_from_paths(
fig = visualize_image_with_mask(
image_data, mask_data, image_affine,
color_map=color_map, show_plot=False
color_map=cm.hot, show_plot=False
)
return fig
def plot_single_slice(
image: np.ndarray,
affine: np.ndarray,
ref_pos: int,
axis: int = 0,
target_path: Union[Path, str] = None,
show_plot: bool = False,
) -> None:
"""
Plot a single slice of one direction.
Parameters
----------
image : np.ndarray
Imag to plot.
affine : np.ndarray
Affine matrix that provides resolution.
ref_pos : int
Reference position for slice.
axis : int, optional
Direction of slice. The default is 0.
target_path : Union[Path, str], optional
Path where to save the plot. The default is None.
show_plot: bool, optional
Flag if plot should be shown. The default is False.
Returns
-------
None
Plot is shown and saved optionally.
"""
t1_min = np.percentile(image, 1)
t1_max = np.percentile(image, 99)
color_scaler = Normalize(vmin=t1_min, vmax=t1_max)
# consider max brain size of 24 cm (is a requirement)
min_edge_length = np.min(image.shape)
# adjust size lenghts, so that all lengths are the same
zoom_x = (image.shape[0] - min_edge_length) // 2
zoom_y = (image.shape[1] - min_edge_length) // 2
zoom_z = (image.shape[2] - min_edge_length) // 2
axis_aspects = [
affine[2, 2] / affine[1, 1],
affine[2, 2] / affine[0, 0],
affine[1, 1] / affine[0, 0],
]
axis_aspect = axis_aspects[axis]
fig, axs = plt.subplots(1, 1, dpi=300, figsize=(20, 10))
if axis == 0:
slice_data = image[ref_pos, zoom_y:-(zoom_y+1), zoom_z:-(zoom_z+1)]
elif axis == 1:
slice_data = image[zoom_x:-(zoom_x+1), ref_pos, zoom_z:-(zoom_z+1)]
else:
slice_data = image[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1), ref_pos]
axs.imshow(
np.fliplr(np.rot90(slice_data)),
cmap='gray',
norm=color_scaler,
)
axs.set_aspect(axis_aspect)
axs.axis('off')
plt.xticks([])
plt.yticks([])
# Remove space between subplots
plt.subplots_adjust(wspace=0, hspace=0)
if target_path:
plt.savefig(
target_path,
bbox_inches="tight",
pad_inches=0,
facecolor="k",
)
if show_plot:
plt.show()
return None
else:
return fig
def plot_single_slice_with_mask(
image: np.ndarray,
mask: np.ndarray,
affine: np.ndarray,
ref_pos: int,
axis: int = 0,
color_map: Colormap = colorblind_friendly_cmap,
target_path: Union[Path, str] = None,
show_plot: bool = False,
) -> None:
"""
Plot a single slice of one direction with mask.
Parameters
----------
image : np.ndarray
Image to plot.
mask : np.ndarray
Discrete mask for overlay.
affine : np.ndarray
Affine matrix that provides resolution.
ref_pos : int
Reference position for slice.
axis : int, optional
Direction of slice. The default is 0.
color_map : Colormap, optional
Colormap to use for mask. The default is colorblind_friendly_cmap.
target_path : Union[Path, str], optional
Path where to save the plot. The default is None.
show_plot : bool, optional
Flag if plot should be shown. The default is False.
Returns
-------
None
Plot is shown and saved optionally.
"""
t1_min = np.percentile(image, 1)
t1_max = np.percentile(image, 99)
color_scaler = Normalize(vmin=t1_min, vmax=t1_max)
params = {"interpolation": "nearest"}
min_edge_length = np.min(image.shape)
# consider max brain size of 24 cm (is a requirement)
# 1 pixel is 1mm (transformed in preprocessing)
# zoom = max(
# 0, min_edge_length -
# int(240 / np.min(np.linalg.norm(affine, axis=0)[:3]))
# )
# adjust size lenghts, so that all lengths are the same
zoom_x = (image.shape[0] - min_edge_length) // 2 # + zoom
zoom_y = (image.shape[1] - min_edge_length) // 2 # + zoom
zoom_z = (image.shape[2] - min_edge_length) // 2 # + zoom
axis_aspects = [
affine[2, 2] / affine[1, 1],
affine[2, 2] / affine[0, 0],
affine[1, 1] / affine[0, 0],
]
axis_aspect = axis_aspects[axis]
fig, axs = plt.subplots(1, 1, dpi=300, figsize=(20, 10))
if axis == 0:
slice_data = image[ref_pos, zoom_y:-(zoom_y+1), zoom_z:-(zoom_z+1)]
slice_mask = mask[ref_pos, zoom_y:-(zoom_y+1), zoom_z:-(zoom_z+1)]
elif axis == 1:
slice_data = image[zoom_x:-(zoom_x+1), ref_pos, zoom_z:-(zoom_z+1)]
slice_mask = mask[zoom_x:-(zoom_x+1), ref_pos, zoom_z:-(zoom_z+1)]
else:
slice_data = image[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1), ref_pos]
slice_mask = mask[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1), ref_pos]
axs.imshow(
np.fliplr(np.rot90(slice_data)),
cmap='gray',
norm=color_scaler,
)
axs.imshow(
np.fliplr(np.rot90(slice_mask)),
color_map,
alpha=0.7
* np.fliplr(np.rot90((slice_mask != 0) * 1.)),
**params
)
axs.set_aspect(axis_aspect)
axs.axis('off')
# axs[i].set_title(f'{ref_pos}', fontsize='xx-small')
plt.xticks([])
plt.yticks([])
# Remove space between subplots
plt.subplots_adjust(wspace=0, hspace=0)
if target_path:
plt.savefig(
target_path,
bbox_inches="tight",
pad_inches=0,
facecolor="k",
)
if show_plot:
plt.show()
return None
else:
return fig
def plot_slice_series_with_mask(
image: np.ndarray,
mask: np.ndarray,
affine: np.ndarray,
fov=None,
axis: int = 0,
num_slices: int = 10,
color_map: Colormap = colorblind_friendly_cmap,
target_path: Union[Path, str] = None,
show_plot: bool = False,
) -> None:
"""
Plot a slice series of one direction with mask.
Parameters
----------
image : np.ndarray
Image to plot.
mask : np.ndarray
Discrete mask for overlay.
affine : np.ndarray
Affine matrix that provides resolution.
fov : TYPE, optional
Field of view to apply. Is calculated if None. The default is None.
axis : int, optional
Direction of slices. The default is 0.
num_slices : int, optional
Number of slices in series. The default is 10.
color_map : Colormap, optional
Colormap to use for mask. The default is colorblind_friendly_cmap.
target_path : Union[Path, str], optional
Path where to save the plot. The default is None.
show_plot : bool, optional
Flag if plot should be shown. The default is False.
Returns
-------
None
Plot is shown and saved optionally.
"""
t1_min = np.percentile(image, 1)
t1_max = np.percentile(image, 99)
color_scaler = Normalize(vmin=t1_min, vmax=t1_max)
params = {"interpolation": "nearest"}
min_edge_length = np.min(image.shape)
# consider max brain size of 24 cm (is a requirement)
# 1 pixel is 1mm (transformed in preprocessing)
# zoom = max(
# 0, min_edge_length -
# int(240 / np.min(np.linalg.norm(affine, axis=0)[:3]))
# )
# adjust size lenghts, so that all lengths are the same
zoom_x = (image.shape[0] - min_edge_length) // 2 # + zoom
zoom_y = (image.shape[1] - min_edge_length) // 2 # + zoom
zoom_z = (image.shape[2] - min_edge_length) // 2 # + zoom
axis_aspects = [
affine[2, 2] / affine[1, 1],
affine[2, 2] / affine[0, 0],
affine[1, 1] / affine[0, 0],
]
axis_aspect = axis_aspects[axis]
if fov is not None:
slice_indices = np.linspace(
fov.start, fov.stop, num_slices, dtype=int)
elif axis == 0:
slice_indices = np.linspace(
zoom_x, image.shape[axis] - zoom_x - 1, num_slices, dtype=int)
elif axis == 1:
slice_indices = np.linspace(
zoom_y, image.shape[axis] - zoom_y - 1, num_slices, dtype=int)
else:
slice_indices = np.linspace(
zoom_z, image.shape[axis] - zoom_z - 1, num_slices, dtype=int)
fig, axs = plt.subplots(1, num_slices, dpi=300, figsize=(20, 10))
for i, ref_pos in enumerate(slice_indices):
if axis == 0:
slice_data = image[ref_pos, zoom_y:-(zoom_y+1), zoom_z:-(zoom_z+1)]
slice_mask = mask[ref_pos, zoom_y:-(zoom_y+1), zoom_z:-(zoom_z+1)]
elif axis == 1:
slice_data = image[zoom_x:-(zoom_x+1), ref_pos, zoom_z:-(zoom_z+1)]
slice_mask = mask[zoom_x:-(zoom_x+1), ref_pos, zoom_z:-(zoom_z+1)]
else:
slice_data = image[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1), ref_pos]
slice_mask = mask[zoom_x:-(zoom_x+1), zoom_y:-(zoom_y+1), ref_pos]
axs[i].imshow(
np.fliplr(np.rot90(slice_data)),
cmap='gray',
norm=color_scaler,
)
axs[i].imshow(
np.fliplr(np.rot90(slice_mask)),
color_map,
alpha=0.7
* np.fliplr(np.rot90((slice_mask != 0) * 1.)),
**params
)
axs[i].set_aspect(axis_aspect)
axs[i].axis('off')
axs[i].set_title(f'{ref_pos}', fontsize='xx-small')
plt.xticks([])
plt.yticks([])
# Remove space between subplots
plt.subplots_adjust(wspace=0, hspace=0)
if target_path:
plt.savefig(
target_path,
bbox_inches="tight",
pad_inches=0,
facecolor="w", # "k",
)
if show_plot:
plt.show()
return None
else:
return fig
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment