Mentions légales du service

Skip to content
Snippets Groups Projects
Commit 1d84d681 authored by LEGRAND Jonathan's avatar LEGRAND Jonathan
Browse files

Add examples of image visualisation with matplotlib.

parent f7eecc29
Branches
Tags
No related merge requests found
# -*- python -*-
# -*- coding: utf-8 -*-
import numpy as np
from vt import vtImage
from vt.tools import shared_data
def plot_3D_array_z_slice(arr, z_slice=None, cmap='gray', title = ""):
"""Plot a z-slice of a given 3D array.
Parameters
----------
arr : np.ndarray
The array to represent.
z_slice : int, optional
The index of the z-sclice to represent.
cmap : str in {'gray', 'viridis'}, optional
Colormap name, all those known by matplolib works. By default use 'gray'.
"""
import matplotlib.pyplot as plt
sh = arr.shape
if z_slice is None:
z_slice = sh[2]//2
plt.figure()
plt.imshow(arr[:, :, z_slice], cmap=cmap)
plt.suptitle(title)
plt.title("Z-slice: {}/{}".format(z_slice, sh[2]))
plt.xlabel('Y-axis')
plt.ylabel('X-axis')
plt.colorbar()
plt.show()
# ------------------------------------------------------------------------------
# Test plotting function with a handmade 3D example:
# ------------------------------------------------------------------------------
xy_shape = 10
mid_xy = xy_shape//2
z_shape = 5
# - Create a 2D array with a diagonal at max value (255):
arr_2d = np.diag(np.repeat(255, xy_shape))
# - For all rows at middle column, replace by 200:
arr_2d[:, mid_xy] = 200
# - For all columns at middle row, replace by 100:
arr_2d[mid_xy, :] = 100
# - Repeat this 2D array `z_shape` times along new dimension to get a 3D array:
arr_3d = np.repeat(arr_2d[:,:,np.newaxis], z_shape, axis=2)
plot_3D_array_z_slice(arr_3d, cmap='viridis', title='Test array')
print("2D array is C-contiguous:", arr_2d.flags.c_contiguous)
print("3D array is C-contiguous:", arr_3d.flags.c_contiguous)
print("Z-slice of 3D array is C-contiguous:", arr_3d[:,:,1].flags.c_contiguous)
print("Z-slice copy of 3D array is C-contiguous:", arr_3d[:,:,1].copy().flags.c_contiguous)
# ------------------------------------------------------------------------------
# Use plotting function with real data:
# ------------------------------------------------------------------------------
# Defines the image to read:
img_name = 'p58-t0_INT_down_interp_2x.tif'
img_path = shared_data(img_name)
# Read this file with vt.vtImage:
vt_im = vtImage(img_path)
sh = vt_im.shape()
print("Image shape is: {}".format(sh))
# Extract the array of data:
arr = vt_im.copy_to_array().copy()
arr = np.reshape(arr.ravel(), sh, order='C')
print("Array shape is: {}".format(arr.shape))
plot_3D_array_z_slice(arr, cmap='gray', title=img_name)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment