Commit 9d6383a4 authored by Unknown's avatar Unknown
Browse files

Image Cleaning notebook bugfix

parent fd1812c2
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Image cleaning and atom finding using pycroscopy # Image cleaning and atom finding using pycroscopy
### Suhas Somnath, Chris R. Smith, Stephen Jesse ### Suhas Somnath, Chris R. Smith, Stephen Jesse
The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials <br> The Center for Nanophase Materials Science and The Institute for Functional Imaging for Materials <br>
Oak Ridge National Laboratory<br> Oak Ridge National Laboratory<br>
1/19/2017 1/19/2017
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Configure the notebook first ## Configure the notebook first
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
!pip install -U numpy scipy skimage h5py matplotlib Ipython ipywidgets pycroscopy !pip install -U numpy scipy skimage h5py matplotlib Ipython ipywidgets pycroscopy
# set up notebook to show plots within the notebook # set up notebook to show plots within the notebook
% matplotlib notebook % matplotlib notebook
# Import necessary libraries: # Import necessary libraries:
# General utilities: # General utilities:
import os import os
import sys import sys
from time import time from time import time
from scipy.misc import imsave from scipy.misc import imsave
# Computation: # Computation:
import numpy as np import numpy as np
import h5py import h5py
from skimage import measure from skimage import measure
from scipy.cluster.hierarchy import linkage, dendrogram from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist from scipy.spatial.distance import pdist
# Visualization: # Visualization:
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib.patches as patches import matplotlib.patches as patches
from mpl_toolkits.axes_grid1 import make_axes_locatable from mpl_toolkits.axes_grid1 import make_axes_locatable
from IPython.display import display, HTML from IPython.display import display, HTML
import ipywidgets as widgets import ipywidgets as widgets
from mpl_toolkits.axes_grid1 import ImageGrid from mpl_toolkits.axes_grid1 import ImageGrid
# Finally, pycroscopy itself # Finally, pycroscopy itself
sys.path.append('..') sys.path.append('..')
import pycroscopy as px import pycroscopy as px
# Make Notebook take up most of page width # Make Notebook take up most of page width
display(HTML(data=""" display(HTML(data="""
<style> <style>
div#notebook-container { width: 95%; } div#notebook-container { width: 95%; }
div#menubar-container { width: 65%; } div#menubar-container { width: 65%; }
div#maintoolbar-container { width: 99%; } div#maintoolbar-container { width: 99%; }
</style> </style>
""")) """))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Load the image that will be cleaned: ## Load the image that will be cleaned:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
image_path = px.io.uiGetFile('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images') image_path = px.io.uiGetFile('*.png *PNG *TIFF * TIF *tif *tiff *BMP *bmp','Images')
print('Working on: \n{}'.format(image_path)) print('Working on: \n{}'.format(image_path))
folder_path, file_name = os.path.split(image_path) folder_path, file_name = os.path.split(image_path)
base_name, _ = os.path.splitext(file_name) base_name, _ = os.path.splitext(file_name)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Make the image file pycroscopy compatible ## Make the image file pycroscopy compatible
Convert the source image file into a pycroscopy compatible hierarchical data format (HDF or .h5) file. This simple translation gives you access to the powerful data functions within pycroscopy Convert the source image file into a pycroscopy compatible hierarchical data format (HDF or .h5) file. This simple translation gives you access to the powerful data functions within pycroscopy
#### H5 files: #### H5 files:
* are like smart containers that can store matrices with data, folders to organize these datasets, images, metadata like experimental parameters, links or shortcuts to datasets, etc. * are like smart containers that can store matrices with data, folders to organize these datasets, images, metadata like experimental parameters, links or shortcuts to datasets, etc.
* are readily compatible with high-performance computing facilities * are readily compatible with high-performance computing facilities
* scale very efficiently from few kilobytes to several terabytes * scale very efficiently from few kilobytes to several terabytes
* can be read and modified using any language including Python, Matlab, C/C++, Java, Fortran, Igor Pro, etc. * can be read and modified using any language including Python, Matlab, C/C++, Java, Fortran, Igor Pro, etc.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Check if an HDF5 file with the chosen image already exists. # Check if an HDF5 file with the chosen image already exists.
# Only translate if it does not. # Only translate if it does not.
h5_path = os.path.join(folder_path, base_name+'.h5') h5_path = os.path.join(folder_path, base_name+'.h5')
need_translation = True need_translation = True
if os.path.exists(h5_path): if os.path.exists(h5_path):
try: try:
h5_file = h5py.File(h5_path, 'r+') h5_file = h5py.File(h5_path, 'r+')
h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data'] h5_raw = h5_file['Measurement_000']['Channel_000']['Raw_Data']
need_translation = False need_translation = False
print('HDF5 file with Raw_Data found. No need to translate.') print('HDF5 file with Raw_Data found. No need to translate.')
except KeyError: except KeyError:
print('Raw Data not found.') print('Raw Data not found.')
else: else:
print('No HDF5 file found.') print('No HDF5 file found.')
if need_translation: if need_translation:
# Initialize the Image Translator # Initialize the Image Translator
tl = px.ImageTranslator() tl = px.ImageTranslator()
# create an H5 file that has the image information in it and get the reference to the dataset # create an H5 file that has the image information in it and get the reference to the dataset
h5_raw = tl.translate(image_path) h5_raw = tl.translate(image_path)
# create a reference to the file # create a reference to the file
h5_file = h5_raw.file h5_file = h5_raw.file
print('HDF5 file is located at {}.'.format(h5_file.filename)) print('HDF5 file is located at {}.'.format(h5_file.filename))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Inspect the contents of this h5 data file ### Inspect the contents of this h5 data file
The file contents are stored in a tree structure, just like files on a contemporary computer. The file contents are stored in a tree structure, just like files on a contemporary computer.
The data is stored as a 2D matrix (position, spectroscopic value) regardless of the dimensionality of the data. The data is stored as a 2D matrix (position, spectroscopic value) regardless of the dimensionality of the data.
In the case of these 2D images, the data is stored as a N x 1 dataset In the case of these 2D images, the data is stored as a N x 1 dataset
The main dataset is always accompanied by four ancillary datasets that explain the position and spectroscopic value of any given element in the dataset. The main dataset is always accompanied by four ancillary datasets that explain the position and spectroscopic value of any given element in the dataset.
In the case of the 2d images, the positions will be arranged as row0-col0, row0-col1.... row0-colN, row1-col0.... In the case of the 2d images, the positions will be arranged as row0-col0, row0-col1.... row0-colN, row1-col0....
The spectroscopic information is trivial since the data at any given pixel is just a scalar value The spectroscopic information is trivial since the data at any given pixel is just a scalar value
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print('Datasets and datagroups within the file:') print('Datasets and datagroups within the file:')
px.io.hdf_utils.print_tree(h5_file) px.io.hdf_utils.print_tree(h5_file)
print('\nThe main dataset:') print('\nThe main dataset:')
print(h5_file['/Measurement_000/Channel_000/Raw_Data']) print(h5_file['/Measurement_000/Channel_000/Raw_Data'])
print('\nThe ancillary datasets:') print('\nThe ancillary datasets:')
print(h5_file['/Measurement_000/Channel_000/Position_Indices']) print(h5_file['/Measurement_000/Channel_000/Position_Indices'])
print(h5_file['/Measurement_000/Channel_000/Position_Values']) print(h5_file['/Measurement_000/Channel_000/Position_Values'])
print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Indices']) print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Indices'])
print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values']) print(h5_file['/Measurement_000/Channel_000/Spectroscopic_Values'])
print('\nMetadata or attributes in a datagroup') print('\nMetadata or attributes in a datagroup')
for key in h5_file['/Measurement_000'].attrs: for key in h5_file['/Measurement_000'].attrs:
print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key])) print('{} : {}'.format(key, h5_file['/Measurement_000'].attrs[key]))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Initialize an object that will perform image windowing on the .h5 file ## Initialize an object that will perform image windowing on the .h5 file
* Note that after you run this, the H5 file is opened. If you want to re-run this cell, close the H5 file first * Note that after you run this, the H5 file is opened. If you want to re-run this cell, close the H5 file first
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Initialize the windowing class # Initialize the windowing class
iw = px.ImageWindow(h5_raw, max_RAM_mb=1024*4) iw = px.ImageWindow(h5_raw, max_RAM_mb=1024*4)
# grab position indices from the H5 file # grab position indices from the H5 file
h5_pos = h5_raw.parent[h5_raw.attrs['Position_Indices']] h5_pos = h5_raw.parent[h5_raw.attrs['Position_Indices']]
# determine the image size: # determine the image size:
num_x = len(np.unique(h5_pos[:,0])) num_x = len(np.unique(h5_pos[:,0]))
num_y = len(np.unique(h5_pos[:,1])) num_y = len(np.unique(h5_pos[:,1]))
# extract figure data and reshape to proper numpy array # extract figure data and reshape to proper numpy array
raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]); raw_image_mat = np.reshape(h5_raw[()], [num_x,num_y]);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Visualize the source image: ## Visualize the source image:
Though the source file is actually grayscale image, we will visualize it using a color-scale Though the source file is actually grayscale image, we will visualize it using a color-scale
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig, axis = plt.subplots(figsize=(10,10)) fig, axis = plt.subplots(figsize=(10,10))
img = axis.imshow(raw_image_mat,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower'); img = axis.imshow(raw_image_mat,cmap=px.plot_utils.cmap_jet_white_center(), origin='lower');
divider = make_axes_locatable(axis) divider = make_axes_locatable(axis)
cax = divider.append_axes("right", size="5%", pad=0.2) cax = divider.append_axes("right", size="5%", pad=0.2)
plt.colorbar(img, cax=cax) plt.colorbar(img, cax=cax)
axis.set_title('Raw Image', fontsize=16); axis.set_title('Raw Image', fontsize=16);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Extract the optimal window size from the image ## Extract the optimal window size from the image
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
num_peaks = 2 num_peaks = 2
win_size , psf_width = iw.window_size_extract(num_peaks, save_plots=False, show_plots=True) win_size , psf_width = iw.window_size_extract(num_peaks, save_plots=False, show_plots=True)
print('Window size = {}'.format(win_size)) print('Window size = {}'.format(win_size))
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Uncomment this line if you need to manually specify a window size # Uncomment this line if you need to manually specify a window size
# win_size = 8 # win_size = 8
# plot a single window # plot a single window
row_offset = int(0.5*(num_x-win_size)) row_offset = int(0.5*(num_x-win_size))
col_offset = int(0.5*(num_y-win_size)) col_offset = int(0.5*(num_y-win_size))
plt.figure() plt.figure()
plt.imshow(raw_image_mat[row_offset:row_offset+win_size, plt.imshow(raw_image_mat[row_offset:row_offset+win_size,
col_offset:col_offset+win_size], col_offset:col_offset+win_size],
cmap=px.plot_utils.cmap_jet_white_center(), cmap=px.plot_utils.cmap_jet_white_center(),
origin='lower'); origin='lower');
# the result should be about the size of a unit cell # the result should be about the size of a unit cell
# if it is the wrong size, just choose on manually by setting the win_size # if it is the wrong size, just choose on manually by setting the win_size
plt.show() plt.show()
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Now break the image into a sequence of small windows ## Now break the image into a sequence of small windows
We do this by sliding a small window across the image. This artificially baloons the size of the data. We do this by sliding a small window across the image. This artificially baloons the size of the data.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
windowing_parms = { windowing_parms = {
'fft_mode': None, # Options are None, 'abs', 'data+abs', or 'complex' 'fft_mode': None, # Options are None, 'abs', 'data+abs', or 'complex'
'win_x': win_size, 'win_x': win_size,
'win_y': win_size, 'win_y': win_size,
'win_step_x': 1, 'win_step_x': 1,
'win_step_y': 1, 'win_step_y': 1,
} }
win_parms_copy = windowing_parms.copy() win_parms_copy = windowing_parms.copy()
if windowing_parms['fft_mode'] is None: if windowing_parms['fft_mode'] is None:
win_parms_copy['fft_mode'] = 'data' win_parms_copy['fft_mode'] = 'data'
h5_wins_grp = px.hdf_utils.check_for_old(h5_raw, 'Windowing', h5_wins_grp = px.hdf_utils.check_for_old(h5_raw, 'Windowing',
win_parms_copy) win_parms_copy)
if h5_wins_grp is None: if h5_wins_grp is None:
print('Windows either do not exist or were created with different parameters') print('Windows either do not exist or were created with different parameters')
t0 = time() t0 = time()
h5_wins = iw.do_windowing(win_x=windowing_parms['win_x'], h5_wins = iw.do_windowing(win_x=windowing_parms['win_x'],
win_y=windowing_parms['win_y'], win_y=windowing_parms['win_y'],
save_plots=False, save_plots=False,
show_plots=False, show_plots=False,
win_fft=windowing_parms['fft_mode']) win_fft=windowing_parms['fft_mode'])
print( 'Windowing took {} seconds.'.format(round(time()-t0, 2))) print( 'Windowing took {} seconds.'.format(round(time()-t0, 2)))
else: else:
print('Taking existing windows dataset') print('Taking existing windows dataset')
h5_wins = h5_wins_grp['Image_Windows'] h5_wins = h5_wins_grp['Image_Windows']
print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape)) print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))
print('Now each position (window) is descibed by a set of pixels') print('Now each position (window) is descibed by a set of pixels')
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Peek at a few random windows # Peek at a few random windows
num_rand_wins = 9 num_rand_wins = 9
rand_positions = np.random.randint(0, high=h5_wins.shape[0], size=num_rand_wins) rand_positions = np.random.randint(0, high=h5_wins.shape[0], size=num_rand_wins)
example_wins = np.zeros(shape=(windowing_parms['win_x'], windowing_parms['win_y'], num_rand_wins), dtype=np.float32) example_wins = np.zeros(shape=(windowing_parms['win_x'], windowing_parms['win_y'], num_rand_wins), dtype=np.float32)
for rand_ind, rand_pos in enumerate(rand_positions): for rand_ind, rand_pos in enumerate(rand_positions):
example_wins[:, :, rand_ind] = np.reshape(h5_wins[rand_pos], (windowing_parms['win_x'], windowing_parms['win_y'])) example_wins[:, :, rand_ind] = np.reshape(h5_wins[rand_pos], (windowing_parms['win_x'], windowing_parms['win_y']))
px.plot_utils.plot_map_stack(example_wins, heading='Example Windows', cmap=px.plot_utils.cmap_jet_white_center(), px.plot_utils.plot_map_stack(example_wins, heading='Example Windows', cmap=px.plot_utils.cmap_jet_white_center(),
title=['Window # ' + str(win_pos) for win_pos in rand_positions]); title=['Window # ' + str(win_pos) for win_pos in rand_positions]);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Performing Singular Value Decompostion (SVD) on the windowed data ## Performing Singular Value Decompostion (SVD) on the windowed data
SVD decomposes data (arranged as position x value) into a sequence of orthogonal components arranged in descending order of variance. The first component contains the most significant trend in the data. The second component contains the next most significant trend orthogonal to all previous components (just the first component). Each component consists of the trend itself (eigenvector), the spatial variaion of this trend (eigenvalues), and the variance (statistical importance) of the component. SVD decomposes data (arranged as position x value) into a sequence of orthogonal components arranged in descending order of variance. The first component contains the most significant trend in the data. The second component contains the next most significant trend orthogonal to all previous components (just the first component). Each component consists of the trend itself (eigenvector), the spatial variaion of this trend (eigenvalues), and the variance (statistical importance) of the component.
Since the data consists of the large sequence of small windows, SVD essentially compares every single window with every other window to find statistically significant trends in the image Since the data consists of the large sequence of small windows, SVD essentially compares every single window with every other window to find statistically significant trends in the image
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# check to make sure number of components is correct: # check to make sure number of components is correct:
num_comp = 1024 num_comp = 1024
num_comp = min(num_comp, num_comp = min(num_comp,
min(h5_wins.shape)*len(h5_wins.dtype)) min(h5_wins.shape)*len(h5_wins.dtype))
h5_svd = px.hdf_utils.check_for_old(h5_wins, 'SVD', {'num_components':num_comp}) h5_svd = px.hdf_utils.check_for_old(h5_wins, 'SVD', {'num_components':num_comp})
if h5_svd is None: if h5_svd is None:
print('SVD was either not performed or was performed with different parameters') print('SVD was either not performed or was performed with different parameters')
h5_svd = px.processing.doSVD(h5_wins, num_comps=num_comp) h5_svd = px.processing.doSVD(h5_wins, num_comps=num_comp)
else: else:
print('Taking existing SVD results') print('Taking existing SVD results')
h5_U = h5_svd['U'] h5_U = h5_svd['U']
h5_S = h5_svd['S'] h5_S = h5_svd['S']
h5_V = h5_svd['V'] h5_V = h5_svd['V']
# extract parameters of the SVD results # extract parameters of the SVD results
h5_pos = iw.hdf.file[h5_wins.attrs['Position_Indices']] h5_pos = iw.hdf.file[h5_wins.attrs['Position_Indices']]
num_rows = len(np.unique(h5_pos[:, 0])) num_rows = len(np.unique(h5_pos[:, 0]))
num_cols = len(np.unique(h5_pos[:, 1])) num_cols = len(np.unique(h5_pos[:, 1]))
num_comp = h5_S.size num_comp = h5_S.size
print("There are a total of {} components.".format(num_comp)) print("There are a total of {} components.".format(num_comp))
print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape)) print('\nRaw data was of shape {} and the windows dataset is now of shape {}'.format(h5_raw.shape, h5_wins.shape))
print('Now each position (window) is descibed by a set of pixels') print('Now each position (window) is descibed by a set of pixels')
plot_comps = 49 plot_comps = 49
U_map_stack = np.reshape(h5_U[:, :plot_comps], [num_rows, num_cols, -1]) U_map_stack = np.reshape(h5_U[:, :plot_comps], [num_rows, num_cols, -1])
V_map_stack = np.reshape(h5_V, [num_comp, win_size, win_size]) V_map_stack = np.reshape(h5_V, [num_comp, win_size, win_size])
V_map_stack = np.transpose(V_map_stack,(2,1,0)) V_map_stack = np.transpose(V_map_stack,(2,1,0))
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Visualize the SVD results ## Visualize the SVD results
##### S (variance): ##### S (variance):
The plot below shows the variance or statistical significance of the SVD components. The first few components contain the most significant information while the last few components mainly contain noise. The plot below shows the variance or statistical significance of the SVD components. The first few components contain the most significant information while the last few components mainly contain noise.
Note also that the plot below is a log-log plot. The importance of each subsequent component drops exponentially. Note also that the plot below is a log-log plot. The importance of each subsequent component drops exponentially.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
fig_S, ax_S = px.plot_utils.plotScree(h5_S[()]); fig_S, ax_S = px.plot_utils.plotScree(h5_S[()]);
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### V (Eigenvectors or end-members) #### V (Eigenvectors or end-members)
The V dataset contains the end members for each component The V dataset contains the end members for each component
%% Cell type:code id: tags: %% Cell type:code id: tags: