%pylab inline
import hyperspy.api as hs
import matplotlib.pylab as pylab
pylab.rcParams['figure.figsize'] = 8, 6 # that's default image size for this interactive session
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
#from ipywidgets.widgets import interactive, fixed, interact
from skimage.exposure import equalize_hist, equalize_adapthist, rescale_intensity
from skimage import filters
import os
StackName = 'Stack.bcf'
BinningFactor = 4
def MakeRGBFromMaps(R,G,B, bits=16, equalize=False, cutnoise=False):
MaxPixelVal = (2**bits)-1
# Make a Signal2D from the three images and copy over the metadata.
x = hs.stack([R,G,B])
x = hs.signals.Signal2D(x).T
x.metadata = R.metadata
x.original_metadata = R.original_metadata
x.metadata.General.title = R.metadata.Sample.xray_lines[0] + '(R) ' + G.metadata.Sample.xray_lines[0] + '(G) ' + B.metadata.Sample.xray_lines[0] + '(B)'
rdata = x.data[:,:,0]
gdata = x.data[:,:,1]
bdata = x.data[:,:,2]
if cutnoise==True:
NoiseCutAggressiveness = 1 # 0 means no cut, 1 means full cut.
rdata[rdata < filters.threshold_triangle(rdata)*NoiseCutAggressiveness] = 0
gdata[gdata < filters.threshold_triangle(gdata)*NoiseCutAggressiveness] = 0
bdata[bdata < filters.threshold_triangle(bdata)*NoiseCutAggressiveness] = 0
if equalize==True:
rdata = equalize_hist(rdata)
gdata = equalize_hist(gdata)
bdata = equalize_hist(bdata)
rdata = rescale_intensity(rdata)*MaxPixelVal
gdata = rescale_intensity(gdata)*MaxPixelVal
bdata = rescale_intensity(bdata)*MaxPixelVal
x.data[:,:,0] = rdata
x.data[:,:,1] = gdata
x.data[:,:,2] = bdata
# Convert to RGB.
if bits==16:
x.change_dtype('uint16')
x.change_dtype('rgb16')
else:
x.change_dtype('uint8')
x.change_dtype('rgb8')
# Copy the axes info over from the R map.
x.axes_manager = R.axes_manager.copy()
return(x)
def EqualizeAxis(fignum=None):
# Because of a bug in Hyperspi, I sometimes have to set the axis to equal after we rebin.
if fignum == None:
fig=plt.gcf()
else:
fig = plt.figure(fignum)
ax = fig.axes
if type(ax) != list:
ax.axis('equal')
else:
for a in ax:
a.axis('equal')
fig.tight_layout()
def RemovePtGaContamination(ElementDict):
'''Make maps without contamination from Pt and Ga in FIB sections.
The maps in ElementDict must contain Pt and Ga maps (obviously...)
'''
ElementDictNoPtGa = dict()
for ElName, ElMap in ElementDict.items():
if ElName in ['Pt', 'Ga']:
ElementDictNoPtGa[ElName] = ElementDict[ElName].deepcopy()
continue
ReducedData = ElementDict[ElName].data.astype(float) - ElementDict['Pt'].data.astype(float) - ElementDict['Ga'].data.astype(float)
ReducedData[ReducedData < 0] = 0
ReducedElMap = ElMap.deepcopy()
ReducedElMap.data = ReducedData
ElementDictNoPtGa[ElName] = ReducedElMap
return ElementDictNoPtGa
def PlotAndSaveRGBAndRGBNoPtGa(RGBElements, equalizeRGB=True, cutnoiseRGB=True, equalizeNoPtGa=True, cutnoiseNoPtGa=True):
Img1 = MakeRGBFromMaps(ElementDict[RGBElements[0]],ElementDict[RGBElements[1]],ElementDict[RGBElements[2]],
equalize=equalizeRGB, cutnoise=cutnoiseRGB)
#Img1.plot()
Img1.save(os.path.join(f'Maps_{BinningFactor}bin', RGBElements[0]+RGBElements[1]+RGBElements[2]+'.tif'), overwrite=True)
Img2 = MakeRGBFromMaps(ElementDictNoPtGa[RGBElements[0]],ElementDictNoPtGa[RGBElements[1]],ElementDictNoPtGa[RGBElements[2]],
equalize=equalizeNoPtGa, cutnoise=cutnoiseNoPtGa)
#Img2.plot()
Img2.save(os.path.join(f'MapsNoPtGa_{BinningFactor}bin', RGBElements[0]+RGBElements[1]+RGBElements[2]+'.tif'), overwrite=True)
hs.plot.plot_images([Img1,Img2], colorbar=None)
#plt.tight_layout()
Populating the interactive namespace from numpy and matplotlib
WARNING:hyperspy_gui_traitsui:The module://ipykernel.pylab.backend_inline matplotlib backend is not compatible with the traitsui GUI elements. For more information, read http://hyperspy.readthedocs.io/en/stable/user_guide/getting_started.html#possible-warnings-when-importing-hyperspy. WARNING:hyperspy_gui_traitsui:The traitsui GUI elements are not available.
HAADF, EDS = hs.load(StackName)
print(f'Stack dimensions are: {EDS.data.shape}.')
if BinningFactor > 1:
EDS = EDS.rebin(scale=(BinningFactor, BinningFactor, 1))
print(f'New stack dimensions are: {EDS.data.shape} with binning: {BinningFactor}')
EDS.plot()
HAADF.save(os.path.join(f'Maps_{BinningFactor}bin', 'HAADF.tif'), overwrite=True)
HAADF.save(os.path.join(f'MapsNoPtGa_{BinningFactor}bin', 'HAADF.tif'), overwrite=True)
Stack dimensions are: (512, 512, 2048). New stack dimensions are: (128, 128, 2048) with binning: 4
print(HAADF.metadata)
print(EDS.metadata)
├── Acquisition_instrument
│ └── TEM
│ ├── beam_energy = 80
│ └── magnification = 115000
├── General
│ ├── original_filename = Stack.bcf
│ └── title = HAADF
├── Sample
│ └── name = 1
└── Signal
├── binned = False
└── signal_type =
├── Acquisition_instrument
│ └── TEM
│ ├── Detector
│ │ └── EDS
│ │ ├── azimuth_angle = 45.0
│ │ ├── detector_type = SuperX
│ │ ├── elevation_angle = 18.0
│ │ ├── energy_resolution_MnKa = 130.0
│ │ └── real_time = 14325.3504
│ ├── Stage
│ │ └── tilt_alpha = 0.0
│ ├── beam_energy = 80
│ └── magnification = 115000
├── General
│ ├── date = 2022-03-18
│ ├── original_filename = Stack.bcf
│ ├── time = 22:59:15
│ └── title = EDX
├── Sample
│ ├── elements = ['Al', 'C', 'Ca', 'Cu', 'Fe', 'Ga', 'Mg', 'Na', 'Ni', 'O', 'Pt', 'S', 'Si', 'Ti']
│ ├── name = 1
│ └── xray_lines = ['Al_Ka', 'C_Ka', 'Ca_Ka', 'Cu_Ka', 'Fe_Ka', 'Ga_Ka', 'Mg_Ka', 'Na_Ka', 'Ni_Ka', 'O_Ka', 'Pt_La', 'S_Ka', 'Si_Ka', 'Ti_Ka']
└── Signal
├── binned = True
├── quantity = X-rays (Counts)
└── signal_type = EDS_TEM
sumspec = EDS.sum()
sumspec.add_lines()
ElLines = ['C_Ka', 'N_Ka', 'O_Ka', 'Na_Ka', 'Pt_La', 'Mg_Ka', 'Al_Ka', 'Si_Ka', 'P_Ka', 'S_Ka', 'Cl_Ka', 'K_Ka', 'Ca_Ka', 'Ti_Ka', 'Cr_Ka', 'Mn_Ka', 'Fe_Ka', 'Ni_Ka', 'Zn_Ka', 'Cu_Ka', 'Ga_Ka' ]
Elements = EDS.get_lines_intensity(ElLines)
Elements = [El.T for El in Elements]
ElementDict = dict()
for El in Elements:
El.change_dtype('uint16')
El.save(os.path.join(f'Maps_{BinningFactor}bin', El.metadata.Sample.xray_lines[0]+'.tif'), overwrite=True)
ElementDict[El.metadata.Sample.elements[0]] = El
#print(f'{El.metadata.Sample.elements[0]}')
ElementDictNoPtGa = RemovePtGaContamination(ElementDict)
ElementsNoPtGa = [El for El in ElementDictNoPtGa.values()]
for El in Elements:
El.save(os.path.join(f'MapsNoPtGa_{BinningFactor}bin', El.metadata.Sample.xray_lines[0]+'.tif'), overwrite=True)
fig = plt.figure(figsize=(20,20))
hs.plot.plot_images(Elements, per_row=ceil(sqrt(len(Elements))), colorbar=None, axes_decor='off', fig=fig)
plt.show()
fig.savefig(os.path.join(f'Maps_{BinningFactor}bin', 'Mosaic.png'))
/Users/Zack/opt/anaconda3/envs/conda37/lib/python3.7/site-packages/hyperspy/drawing/utils.py:890: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later. ax = f.add_subplot(rows, per_row, idx + 1)
fig = plt.figure(figsize=(20,20))
hs.plot.plot_images(ElementsNoPtGa, per_row=ceil(sqrt(len(ElementsNoPtGa))), colorbar=None, axes_decor='off', fig=fig)
plt.show()
fig.savefig(os.path.join(f'MapsNoPtGa_{BinningFactor}bin', 'Mosaic.png'))
PlotAndSaveRGBAndRGBNoPtGa(['Fe', 'Mg', 'O'], equalizeRGB=True, cutnoiseRGB=True)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Fe', 'Si', 'S'])
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Fe', 'Ni', 'S'])
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Mg', 'Ni', 'Si'])
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Ni', 'O', 'Mg'])
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['C', 'N', 'O'])
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['C', 'O', 'Si'], equalizeNoPtGa=True, cutnoiseNoPtGa=True)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['C', 'Fe', 'Mg'], equalizeNoPtGa=True, cutnoiseNoPtGa=True)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Al', 'Mg', 'O'], equalizeNoPtGa=True, cutnoiseNoPtGa=True)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Al', 'Ca', 'Cr'], equalizeNoPtGa=False, cutnoiseNoPtGa=False)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['Na', 'K', 'Al'], equalizeNoPtGa=False, cutnoiseNoPtGa=False)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
PlotAndSaveRGBAndRGBNoPtGa(['C', 'Al', 'Mg'], equalizeNoPtGa=False, cutnoiseNoPtGa=False)
[########################################] | 100% Completed | 0.1s [########################################] | 100% Completed | 0.1s
%%javascript
IPython.notebook.save_notebook()
!jupyter-nbconvert --to html "Plot Bruker Stack.ipynb"
[NbConvertApp] Converting notebook Plot Bruker Stack.ipynb to html [NbConvertApp] Writing 2844098 bytes to Plot Bruker Stack.html
%%javascript
IPython.notebook.save_notebook()