示例#1
0
def _transform():
    global IM, AIM, canvas, transform, text

    method = transform.get()

    text.delete(1.0, tk.END)
    text.insert(tk.END,"inverse Abel transform: {:s}\n".format(method))
    if "basex" in method:
        text.insert(tk.END,"  first time calculation of the basis functions may take a while ...\n")
    if "direct" in method:
       text.insert(tk.END,"   calculation is slowed if Cython unavailable ...\n")
    canvas.show()

    # inverse Abel transform of whole image
    if method == 'linbasex':
        AIM = abel.Transform(IM, method=method, direction="inverse",
                             symmetry_axis=None,
                             transform_options=dict(return_Beta=True))
    else:
        AIM = abel.Transform(IM, method=method, direction="inverse",
                             symmetry_axis=None,
                             transform_options=dict(basis_dir='bases'))

    f.clf()
    a = f.add_subplot(111)
    a.imshow(AIM.transform, vmin=0, vmax=AIM.transform.max()/5.0)
    canvas.show()
示例#2
0
def test_linbasex_forward_dribinski_image():
    """ Check hansenlaw forward/inverse transform
        using BASEX sample image, comparing speed distributions
    """

    # BASEX sample image
    IM = abel.tools.analytical.SampleImage(n=1001, name="dribinski").func

    # forward Abel transform
    fIM = abel.Transform(IM, method='hansenlaw', direction='forward')

    # inverse Abel transform
    ifIM = abel.Transform(fIM.transform,
                          method='linbasex',
                          transform_options=dict(legendre_orders=[0, 2],
                                                 proj_angles=[0, np.pi / 2],
                                                 return_Beta=True))

    # speed distribution
    orig_radial, orig_speed = abel.tools.vmi.angular_integration_3D(IM)

    radial = ifIM.radial
    speed = ifIM.Beta[0]

    orig_speed /= orig_speed[1:60].max()
    speed /= speed[1:60].max()

    assert np.allclose(orig_speed[1:60], speed[1:60], rtol=0, atol=0.1)
示例#3
0
    def _transform(self):
        # self.method = Abel_methods[self.transform_method.get()]
        self.method = self.transform.get()
        self.fi = self.direction.get()

        if self.method != self.old_method or self.fi != self.old_fi:
            # Abel transform of whole image
            self.text.insert(
                tk.END,
                "\n{:s} {:s} Abel transform:".format(self.method, self.fi))
            if self.method == "basex":
                self.text.insert(
                    tk.END, "\nbasex: first time calculation of the basis"
                    " functions may take a while ...")
            elif self.method == "direct":
                self.text.insert(
                    tk.END,
                    "\ndirect: calculation is slowed if Cython unavailable ..."
                )
            self.canvas.draw()

            if self.method == 'linbasex':
                self.AIM = abel.Transform(
                    self.IM,
                    method=self.method,
                    direction=self.fi,
                    transform_options=dict(return_Beta=True))
            else:
                self.AIM = abel.Transform(
                    self.IM,
                    method=self.method,
                    direction=self.fi,
                    transform_options=dict(basis_dir='bases'),
                    symmetry_axis=None)
            self.rmin.delete(0, tk.END)
            self.rmin.insert(0, self.rmx[0])
            self.rmax.delete(0, tk.END)
            self.rmax.insert(0, self.rmx[1])

        if self.old_method != self.method or self.fi != self.old_fi or\
           self.action not in ["speed", "anisotropy"]:
            self.plt[2].set_title(self.method +
                                  " {:s} Abel transform".format(self.fi),
                                  fontsize=10)
            self.plt[2].imshow(self.AIM.transform,
                               vmin=0,
                               vmax=self.AIM.transform.max() / 5.0)
            # self.f.colorbar(self.c.get_children()[2], ax=self.f.gca())
            # self.text.insert(tk.END, "{:s} inverse Abel transformed image"
            # .format(self.method))

        self.text.see(tk.END)
        self.old_method = self.method
        self.old_fi = self.fi
        self.canvas.draw()
def Soot_propensity(ruta,logger):
  try:
      img = misc.imread(ruta) # Leemos la imagen  #ruta 'imagenes_llama/Llama (1).tiff'
      img= rescale(img/255, 0.5,mode='constant')#reescalar la imagen, nomalizacion de 0-1

      img_mono = img[:,:,0]*0.2989 + img[:,:,1]*0.5870 + img[:,:,2]*0.1140#transformacion rgb-grey
      foreground= (img_mono >= 0.02)#obtencion de la mascara
      img_mono2 = img_mono*foreground/1000e-6 #aplicamos mascara y reescalamos por tiempo de exposicion
   
      inverse_abel = abel.Transform(img_mono2, direction='inverse', method='three_point').transform
      inverse_abel=inverse_abel*foreground #aplicamos mascara a abel
    
      [uu,vv]=inverse_abel.shape #calculamos tamano de abel
      fv_temp=calculo_soot_propensity(img_mono ,inverse_abel,vv,uu)#calculamos fraccion de hollin.
      medi=calculo_de_medidas_estadisticas(fv_temp)
      return medi #fin de la funcion
  
  except: #excepcion en caso de que el algoritmo falle
      medi=['0','0','0','0','0','0','0','0','0','0','0','0']
      logger.error("Error calculando soot propensity") 
      #print("error en el calculo de soot propensity")
      return medi
    def inverse_abel_transform(self, plotting=False, method="hansenlaw"):
        # Flip the image, so the abel transform work
        image = self.phase.T

        # Using the inbuilt gaussian method to find the axis
        self.inverse_abel = abel.Transform(
            image,
            #center = (50, 200),
            method=method,
            center="gaussian",
            center_options={
                'axes': 1,
                "verbose": True
            },
            direction='inverse',
            verbose=True).transform.T

        if plotting:
            plt.figure(figsize=(8, 4))
            plt.imshow(
                self.inverse_abel,
                cmap=plt.cm.seismic,
                norm=func.MidpointNormalize(midpoint=0),
            )
            cbar = plt.colorbar()
            cbar.set_label("Raw Abel Transform")
            plt.title("Inverse Abel Transform")
            plt.xlabel("Pixels")
            plt.ylabel("Pixels")
            plt.show()

            lineout_ave = np.average(self.inverse_abel[10:-10, :], axis=0)
            plt.figure(figsize=(8, 4))

            plt.plot(
                np.arange(len(lineout_ave)) * self.sizePerPixel * 1e3,
                lineout_ave)
            plt.xlabel("Distance (mm)")
            plt.show()
    def BASEX(self):
        """ Calculates the inverse Abel transform of the symmetrised
        and cropped image by calling routines in the abel module

        Returns:
        ReconstructedImage - 2D slice of the 3D reconstructed ion image (ndarray)
        PES - Tuple containing the speed distribution vs. pixel radius

        """
        try:
            self.ReconstructedImage = abel.Transform(self.BlurredImage,
                                                direction="inverse",
                                                method="basex",
                                                center=self.ImageCentre).transform
            r, speed = abel.tools.vmi.angular_integration(self.ReconstructedImage,
                                                          dr=self.CalibrationConstant)
            self.PES = pd.DataFrame(data=speed,
                                    columns=["P(s)"],
                                    index=r)
        except AttributeError:
            print " Image has not been centred, blurred or calconstant-less."
            print " Call BlurImage and FindCentre before running."
            pass
示例#7
0
import abel
original     = abel.tools.analytical.SampleImage().image
forward_abel = abel.Transform(original, direction='forward', 
                              method='hansenlaw'  ).transform
inverse_abel = abel.Transform(forward_abel, direction='inverse',
                              method='three_point', 
                    transform_options=dict(basis_dir='bases')).transform


# plot the original and transform
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(1, 2, figsize=(6, 4))
axs[0].imshow(forward_abel, clim=(0, np.max(forward_abel)*0.6), origin='lower', extent=(-1,1,-1,1))
axs[1].imshow(inverse_abel, clim=(0, np.max(inverse_abel)*0.4), origin='lower', extent=(-1,1,-1,1))

axs[0].set_title('Forward Abel Transform')
axs[1].set_title('Inverse Abel Transform')

plt.tight_layout()
plt.savefig('plot_example.png', dpi=150)
plt.show()
示例#8
0
output_image = name + '_inverse_Abel_transform_HansenLaw.png'
output_text  = name + '_speeds_HansenLaw.dat'
output_plot  = 'plot_' + name + '_comparison_HansenLaw.png'

print('Loading ' + filename)
#im = np.loadtxt(filename)
im = plt.imread(filename) 
(rows,cols) = np.shape(im)
print ('image size {:d}x{:d}'.format(rows,cols))


# Step 2: perform the Hansen & Law transform!
print('Performing Hansen and Law inverse Abel transform:')

recon = abel.Transform(im, method="hansenlaw", direction="inverse", 
                       symmetry_axis=None, verbose=True, 
                       center=(240,340)).transform
                       
r, speeds = abel.tools.vmi.angular_integration(recon)

# Set up some axes
fig = plt.figure(figsize=(15,4))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

# raw data
im1 = ax1.imshow(im, origin='lower', aspect='auto')
fig.colorbar(im1, ax=ax1, fraction=.1, shrink=0.9, pad=0.03)
ax1.set_xlabel('x (pixels)')
ax1.set_ylabel('y (pixels)')
示例#9
0
im_y = R - np.arange(float(N))[:, None]
im_r = np.sqrt(im_x**2 + im_y**2)
# simulate beam-block shadow
im = im / (1 + np.exp(-(im_r - block_r)))
im[:R] *= 1 / (1 + np.exp(-(np.abs(im_x) - block_w)))

# create mask that fully covers beam-block shadow
mask_r = block_r + 5
mask_w = block_w + 5
mask = np.ones_like(im)
mask[im_r < mask_r] = 0
mask[:R, R - mask_w:R + mask_w] = 0

# reconstruct "as is" by a general Abel-transform method
rec_abel = abel.Transform(im,
                          method='two_point',
                          transform_options=dict(basis_dir='bases')).transform
# extract profiles "as is"
r_abel, P0_abel, P2_abel = rharmonics(rec_abel)
# extract profiles from masked reconstruction
r_abel_masked, P0_abel_masked, P2_abel_masked = rharmonics(rec_abel,
                                                           weights=mask)

# reconstruct masked image with rBasex
rec_rbasex, distr_rbasex = rbasex_transform(im, weights=mask)
r_rbasex, P0_rbasex, P2_rbasex = distr_rbasex.rharmonics()

# plotting...
plt.figure(figsize=(7, 7))

plt.cm.hot.set_bad('lightgray', 1.0)
示例#10
0
IM = np.loadtxt(imagefile)
# use scipy.misc.imread(filename) to load image formats (.png, .jpg, etc)

rows, cols = IM.shape    # image size

# Image center should be mid-pixel, i.e. odd number of colums
if cols % 2 != 1: 
    print ("even pixel width image, make it odd and re-adjust image center")
    IM = abel.tools.center.center_image(IM, method="slice")
    rows, cols = IM.shape   # new image size

r2 = rows//2   # half-height image size
c2 = cols//2   # half-width image size

# Hansen & Law inverse Abel transform
AIM = abel.Transform(IM, method="hansenlaw", direction="inverse",
                     symmetry_axis=None).transform

# PES - photoelectron speed distribution  -------------
print('Calculating speed distribution:')

r, speed  = abel.tools.vmi.angular_integration(AIM)

# normalize to max intensity peak
speed /= speed[200:].max()  # exclude transform noise near centerline of image

# PAD - photoelectron angular distribution  ------------
print('Calculating angular distribution:')
# radial ranges (of spectral features) to follow intensity vs angle
# view the speed distribution to determine radial ranges
r_range = [(93, 111), (145, 162), (255, 280), (330, 350), (350, 370), 
           (370, 390), (390, 410), (410, 430)]
示例#11
0
#######################################################################
#
# example_circularize_image.py
#
# O- sample image -> forward Abel + distortion = measured VMI
#  measured VMI   -> inverse Abel transform -> speed distribution
# Compare disorted and circularized speed profiles
#
#######################################################################


# sample image -----------
IM = abel.tools.analytical.SampleImage(n=511, name='Ominus', sigma=2).func

# forward transform == what is measured
IMf = abel.Transform(IM, method='hansenlaw', direction="forward").transform

# flower image distortion
def flower_scaling(theta, freq=2, amp=0.1):
    return 1 + amp * np.sin(freq * theta)**4

# distort the image
IMdist = circularize(IMf, radial_correction_function=flower_scaling)

# circularize ------------
IMcirc, sla, sc, scspl = circularize_image(IMdist,
                                           method='lsq', dr=0.5, dt=0.1,
                                           tol=0, return_correction=True)

# inverse Abel transform for distored and circularized images ---------
AIMdist = abel.Transform(IMdist, method="three_point").transform
示例#12
0
IM = np.loadtxt("data/O2-ANU1024.txt.bz2")

rows, cols = IM.shape    # image size

# Image center-line should be mid-pixel, i.e. odd number of columns
if cols % 2 == 0: 
    print ("HL: even pixel width image, re-adjusting image centre\n"
           "    using `slice` method, returning odd-width size image")
    IM = abel.tools.center.center_image(IM, center="slice", odd_size=True)
    rows, cols = IM.shape   # new image size

# dr=0.5 may help reduce pixel grid coarseness
# NB remember to also pass to angular_integration
AIM = abel.Transform(IM, method='hansenlaw',
                     use_quadrants=(True, True, True, True),
                     symmetry_axis=None,
                     transform_options=dict(dr=0.5),
                     verbose=True).transform

radial, speeds  = abel.tools.vmi.angular_integration(AIM, dr=0.5)

# convert to photoelectron spectrum vs binding energy
# conversion factors depend on measurement parameters
eBE, PES = abel.tools.vmi.toPES(radial, speeds,
                                energy_cal_factor=1.209e-5,
                                photon_energy=1.0e7/454.5, Vrep=-2200,
                                zoom=0.5)

# Set up some axes
fig = plt.figure(figsize=(15, 4))
ax1 = plt.subplot2grid((1, 3), (0, 0))
示例#13
0
# `center=convolution` takes care of this

un = [0, 2]  # spherical harmonic orders
proj_angles = np.arange(0, 2*np.pi, np.pi/20) # projection angles
# adjust these parameter to 'improve' the look
smoothing = 0.9  # smoothing Gaussian 1/e width
threshold = 0.01 # exclude small amplitude Newton spheres
# no need to change these
radial_step = 1
clip = 0

# linbasex inverse Abel transform
LIM = abel.Transform(IM, method="linbasex", center="convolution",
                     center_options=dict(square=True),
                     transform_options=dict(basis_dir=None, return_Beta=True,
                                            legendre_orders=un,
                                            proj_angles=proj_angles,
                                            smoothing=smoothing,
                                            radial_step=radial_step, clip=clip,
                                            threshold=threshold)) 

# angular, and radial integration - direct from `linbasex` transform
# as class attributes
radial = LIM.radial
speed  = LIM.Beta[0]
anisotropy = LIM.Beta[1]

# normalize to max intensity peak i.e. max peak height = 1
speed /= speed[200:].max()  # exclude transform noise near centerline of image

# plots of the analysis
fig = plt.figure(figsize=(11, 5))
示例#14
0
# Step 1: Load an image file as a numpy array
print('Loading ' + filename)
raw_data = plt.imread(filename).astype('float64')

# Step 2: Specify the center in y,x (vert,horiz) format
center = (245,340)
# or, use automatic centering
# center = 'com'
# center = 'gaussian'

# Step 3: perform the BASEX transform!
print('Performing the inverse Abel transform:')

recon = abel.Transform(raw_data, direction='inverse', method='basex',
                       center=center, transform_options=dict(basis_dir='bases'),
                       verbose=True).transform
                      
speeds = abel.tools.vmi.angular_integration(recon)

# Set up some axes
fig = plt.figure(figsize=(15,4))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

# Plot the raw data
im1 = ax1.imshow(raw_data,origin='lower',aspect='auto')
fig.colorbar(im1,ax=ax1,fraction=.1,shrink=0.9,pad=0.03)
ax1.set_xlabel('x (pixels)')
ax1.set_ylabel('y (pixels)')
methods = ['basex','hansenlaw','direct','two_point','three_point','onion_peeling','onion_bordas','psana-pop']
imgs = {}
ts = {}
for i, method in enumerate(methods):
    print(method,'#############################')
    if method =='psana-pop':
        t0 = time.time()
        pop.Peel(img)
        imgs[method] = pop.GetSlice()
        t1 = time.time()
        ts[method] = t1-t0
        continue
     
    t0 = time.time()
    imgs[method] = abel.Transform(img, direction='inverse', method=method).transform
    imgs[method][imgs[method]<0]=0
    imgs[method] = imgs[method]/imgs[method].max()    
    t1 = time.time()
    ts[method] = t1-t0
    
fig = plt.figure(figsize=(12,20))
for i, method in enumerate(methods):
    plt.subplot(4,2,i+1)
    im = plt.imshow(imgs[method])
    ax = plt.gca()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax)
    if method !='psana-pop':
        ax.set_title('PyAbel-'+method+':'+str(round(ts[method],2))+' s')
示例#16
0
          " center_image()".format(cols))
    im = abel.tools.center.center_image(im, center="slice", odd_size=True)
    # alternative
    #im = shift(im,(0.5, 0.5))
    #im = im[:-1, 1::]  # drop left col, bottom row
    (rows, cols) = np.shape(im)

c2 = cols//2   # half-image width
r2 = rows//2   # half-image height
print('image size {:d}x{:d}'.format(rows, cols))

# Hansen & Law inverse Abel transform
print('Performing Hansen and Law inverse Abel transform:')

# quad = (True ... => combine the 4 quadrants into one
reconH = abel.Transform(im, method="hansenlaw", direction="inverse",
                        verbose=True, symmetry_axis=None).transform
rH, speedsH = abel.tools.vmi.angular_integration_3D(reconH)

# Basex inverse Abel transform
print('Performing basex inverse Abel transform:')
reconB = abel.Transform(im, method="basex", direction="inverse",
                        verbose=True, symmetry_axis=None).transform
rB, speedsB = abel.tools.vmi.angular_integration_3D(reconB)

# plot the results - VMI, inverse Abel transformed image, speed profiles
# Set up some axes
fig = plt.figure(figsize=(15, 4.5))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)
示例#17
0
# === linbasex transform ===================================
legendre_orders = [0, 2, 4]  # Legendre polynomial orders
proj_angles = range(0, 180, 10)  # projection angles in 10 degree steps
radial_step = 1  # pixel grid
smoothing = 0.9  # smoothing 1/e-width for Gaussian convolution smoothing
threshold = 0.2  # threshold for normalization of higher order Newton spheres
clip = 0  # clip first vectors (smallest Newton spheres) to avoid singularities

# linbasex method - center and center_options ensure image has odd square shape
LIM = abel.Transform(IM,
                     method='linbasex',
                     origin='slice',
                     center_options=dict(square=True),
                     transform_options=dict(basis_dir=None,
                                            proj_angles=proj_angles,
                                            radial_step=radial_step,
                                            smoothing=smoothing,
                                            threshold=threshold,
                                            clip=clip,
                                            return_Beta=True,
                                            verbose=True))

# === Hansen & Law inverse Abel transform ==================
HIM = abel.Transform(IM,
                     origin="slice",
                     method="hansenlaw",
                     symmetry_axis=None,
                     angular_integration=True)

# speed distribution
radial, speed = HIM.angular_integration
print('Loading ' + filename)
raw_data = plt.imread(filename).astype('float64')

# Step 2: Specify the center in y,x (vert,horiz) format
center = (245, 340)
# or, use automatic centering
# center = 'com'
# center = 'gaussian'

# Step 3: perform the BASEX transform!
print('Performing the inverse Abel transform:')

recon = abel.Transform(raw_data,
                       direction='inverse',
                       method='basex',
                       center=center,
                       transform_options={
                           'basis_dir': './'
                       },
                       verbose=True).transform

speeds = abel.tools.vmi.angular_integration(recon)

# Set up some axes
fig = plt.figure(figsize=(15, 4))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

# Plot the raw data
im1 = ax1.imshow(raw_data, origin='lower', aspect='auto')
fig.colorbar(im1, ax=ax1, fraction=.1, shrink=0.9, pad=0.03)
示例#19
0
import matplotlib.pyplot as plt

# Dribinski sample image
IM = abel.tools.analytical.SampleImage(n=501).image

# split into quadrants
origQ = abel.tools.symmetry.get_image_quadrants(IM)

# speed distribution
orig_speed = abel.tools.vmi.angular_integration(origQ[0], origin=(0, 0))

# forward Abel projection
fIM = abel.Transform(IM,
                     direction="forward",
                     method="openAbel",
                     transform_options={
                         'method': 3,
                         'order': 3
                     }).transform

# split projected image into quadrants
Q = abel.tools.symmetry.get_image_quadrants(fIM)
Q0 = Q[0].copy()

# openAbel inverse Abel transform
borQ0 = abel.openAbel.openAbel_transform(Q0, method=3, order=3)
# speed distribution
bor_speed = abel.tools.vmi.angular_integration(borQ0, origin=(0, 0))

plt.plot(*orig_speed, linestyle='dashed', label="Dribinski sample")
plt.plot(bor_speed[0], bor_speed[1], label="openAbel")
示例#20
0
from lmfit import Model, Parameters
from photutils.isophote import EllipseGeometry, Ellipse

#=======================
#Performing the inverse Abel transformation over the bulge 2D image
#=======================

#This must be a 2D model image of the bulge to be transformed
image = '/home/elismar/Documentos/Fisica/IC/imfit-1.7.1/ngc2992/images/2MASS/bulge_model.fits'
image = fits.getdata(image)

#The center pixel coordinates of the bulge
x0 = 98.5
y0 = 98.5
bulge_3D = abel.Transform(image,
                          direction='inverse',
                          method='three_point',
                          center=(y0, x0)).transform

#=======================
#Fitting ellipses to the 3D image in order to get its brigthness profile
#=======================

# geometry = EllipseGeometry(x0=98, y0=98, sma=15, eps=0.19, pa=(np.pi/180)*226)
geometry = EllipseGeometry(x0=98, y0=98, sma=15, eps=0.0, pa=0)

ellipse = Ellipse(bulge_3D, geometry)
isolist = ellipse.fit_image(fix_pa=True, fix_eps=True)

#========================
#Converting to mass profile
#========================
示例#21
0
im_x = np.arange(float(N)) - R
im_y = R - np.arange(float(N))[:, None]
im_r = np.sqrt(im_x**2 + im_y**2)
# simulate beam-block shadow
im = im / (1 + np.exp(-(im_r - block_r)))
im[:R] *= 1 / (1 + np.exp(-(np.abs(im_x) - block_w)))

# create mask that fully covers beam-block shadow
mask_r = block_r + 5
mask_w = block_w + 5
mask = np.ones_like(im)
mask[im_r < mask_r] = 0
mask[:R, R - mask_w:R + mask_w] = 0

# reconstruct "as is" by a general Abel-transform method
rec_abel = abel.Transform(im, method='two_point').transform
# extract profiles "as is"
r_abel, P0_abel, P2_abel = rharmonics(rec_abel)
# extract profiles from masked reconstruction
r_abel_masked, P0_abel_masked, P2_abel_masked = rharmonics(rec_abel,
                                                           weights=mask)

# reconstruct masked image with rBasex
rec_rbasex, distr_rbasex = rbasex_transform(im, weights=mask)
r_rbasex, P0_rbasex, P2_rbasex = distr_rbasex.rharmonics()

# plotting...
plt.figure(figsize=(7, 7))

cmap_hot = copy(plt.cm.hot)
cmap_hot.set_bad('lightgray')
示例#22
0
import abel
original     = abel.tools.analytical.sample_image()
forward_abel = abel.Transform(original, direction='forward', 
                              method='hansenlaw'  ).transform
inverse_abel = abel.Transform(forward_abel, direction='inverse',
                              method='three_point').transform


# plot the original and transform
import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(1, 2, figsize=(6, 4))
axs[0].imshow(forward_abel, clim=(0, np.max(forward_abel)*0.6), origin='lower', extent=(-1,1,-1,1))
axs[1].imshow(inverse_abel, clim=(0, np.max(inverse_abel)*0.4), origin='lower', extent=(-1,1,-1,1))

axs[0].set_title('Forward Abel Transform')
axs[1].set_title('Inverse Abel Transform')

plt.tight_layout()
plt.savefig('example.png', dpi=150)
plt.show()
示例#23
0
# use scipy.misc.imread(filename) to load image formats (.png, .jpg, etc)
print('HL: loading "data/O2-ANU1024.txt.bz2"')
imagefile = bz2.BZ2File('data/O2-ANU1024.txt.bz2')
IM = np.loadtxt(imagefile)

rows, cols = IM.shape  # image size

# center image returning odd size
IMc = abel.tools.center.center_image(IM, method='com')

# dr=0.5 may help reduce pixel grid coarseness
# NB remember to also pass as an option to angular_integration
AIM = abel.Transform(IMc,
                     method='hansenlaw',
                     use_quadrants=(True, True, True, True),
                     symmetry_axis=None,
                     transform_options=dict(dr=0.5, align_grid=False),
                     angular_integration=True,
                     angular_integration_options=dict(dr=0.5),
                     verbose=True)

# convert to photoelectron spectrum vs binding energy
# conversion factors depend on measurement parameters
eBE, PES = abel.tools.vmi.toPES(*AIM.angular_integration,
                                energy_cal_factor=1.204e-5,
                                photon_energy=1.0e7 / 454.5,
                                Vrep=-2200,
                                zoom=IM.shape[-1] / 2048)

# Set up some axes
fig = plt.figure(figsize=(15, 4.5))
ax1 = plt.subplot2grid((1, 3), (0, 0))
示例#24
0
# Step 1: Load an image file as a numpy array
print('Loading ' + filename)
raw_data = plt.imread(filename).astype('float64')

# Step 2: Specify the origin in (row, col) format
origin = (245, 340)
# or, use automatic centering
# origin = 'com'
# origin = 'gaussian'

# Step 3: perform the BASEX transform!
print('Performing the inverse Abel transform:')

recon = abel.Transform(raw_data,
                       direction='inverse',
                       method='basex',
                       origin=origin,
                       verbose=True).transform

speeds = abel.tools.vmi.angular_integration_3D(recon)

# Set up some axes
fig = plt.figure(figsize=(15, 4))
ax1 = plt.subplot(131)
ax2 = plt.subplot(132)
ax3 = plt.subplot(133)

# Plot the raw data
im1 = ax1.imshow(raw_data, origin='lower')
fig.colorbar(im1, ax=ax1, fraction=0.1, shrink=0.9, pad=0.03)
ax1.set_xlabel('x (pixels)')
示例#25
0
x = np.linspace(-5, 5, xsize)
y = np.linspace(-15, 15, ysize)
plt.pcolormesh(x, y, testArray)
plt.colorbar()
plt.show()

for i, yp in enumerate(y):
    for j, xp in enumerate(x):
        value = np.exp(-((yp) / 3.)**2) * abs(xp + 5)
        testArray[i][j] = value

testArray = (testArray / testArray.max()) * np.pi
plt.pcolormesh(x, y, testArray)
plt.colorbar()
plt.show()

testArray = testArray.T
inverse_abel = abel.Transform(
    testArray,  #center = (50, 200),
    center="gaussian",
    center_options={
        'axes': 1,
        "verbose": True
    },
    direction='inverse',
    verbose=True).transform.T

plt.pcolormesh(x, y, inverse_abel)
plt.colorbar()
plt.show()
示例#26
0
#######################################################################
#
# example_circularize_image.py
#
# O- sample image -> forward Abel + distortion = measured VMI
#  measured VMI   -> inverse Abel transform -> speed distribution
# Compare disorted and circularized speed profiles
#
#######################################################################

# sample image -----------
IM = abel.tools.analytical.SampleImage(n=511, name='Ominus', sigma=2).image

# forward transform == what is measured
IMf = abel.Transform(IM, method='hansenlaw', direction="forward").transform


# flower image distortion
def flower_scaling(theta, freq=2, amp=0.1):
    return 1 + amp * np.sin(freq * theta)**4


# distort the image
IMdist = abel.tools.circularize.circularize(
    IMf, radial_correction_function=flower_scaling)

# circularize ------------
IMcirc, sla, sc, scspl = abel.tools.circularize.circularize_image(
    IMdist, method='lsq', dr=0.5, dt=0.1, smooth=0, return_correction=True)
    # alternative
    #im = shift(im,(0.5,0.5))
    #im = im[:-1, 1::]  # drop left col, bottom row
    (rows, cols) = np.shape(im)

c2 = cols // 2  # half-image width
r2 = rows // 2  # half-image height
print('image size {:d}x{:d}'.format(rows, cols))

# Hansen & Law inverse Abel transform
print('Performing Hansen and Law inverse Abel transform:')

# quad = (True ... => combine the 4 quadrants into one
reconH = abel.Transform(im,
                        method="hansenlaw",
                        direction="inverse",
                        verbose=True,
                        symmetry_axis=None).transform
rH, speedsH = abel.tools.vmi.angular_integration(reconH)

# Basex inverse Abel transform
print('Performing basex inverse Abel transform:')
reconB = abel.Transform(im,
                        method="basex",
                        direction="inverse",
                        verbose=True,
                        symmetry_axis=None,
                        transform_options=dict(basis_dir='bases')).transform
rB, speedsB = abel.tools.vmi.angular_integration(reconB)

# plot the results - VMI, inverse Abel transformed image, speed profiles
示例#28
0
IM = abel.tools.analytical.SampleImage(n).image

# split into quadrants
origQ = abel.tools.symmetry.get_image_quadrants(IM)

# speed distribution of original image
orig_speed = abel.tools.vmi.angular_integration(origQ[0], origin=(0, 0))
scale_factor = orig_speed[1].max()

plt.plot(orig_speed[0],
         orig_speed[1] / scale_factor,
         linestyle='dashed',
         label="Dribinski sample")

# forward Abel projection
fIM = abel.Transform(IM, direction="forward", method="hansenlaw").transform

# split projected image into quadrants
Q = abel.tools.symmetry.get_image_quadrants(fIM)

dasch_transform = {\
"two_point": abel.dasch.two_point_transform,
"three_point": abel.dasch.three_point_transform,
"onion_peeling": abel.dasch.onion_peeling_transform}

for method in dasch_transform.keys():
    Q0 = Q[0].copy()
    # method inverse Abel transform
    AQ0 = dasch_transform[method](Q0, basis_dir='bases')
    # speed distribution
    speed = abel.tools.vmi.angular_integration(AQ0, origin=(0, 0))
legendre_orders = [0, 2, 4]  # Legendre polynomial orders
proj_angles = np.arange(0, np.pi / 2,
                        np.pi / 10)  # projection angles in 10 degree steps
radial_step = 1  # pixel grid
smoothing = 1  # smoothing 1/e-width for Gaussian convolution smoothing
threshold = 0.2  # threshold for normalization of higher order Newton spheres
clip = 0  # clip first vectors (smallest Newton spheres) to avoid singularities

# linbasex method - center ensures image has odd square shape
#                 - speed and anisotropy parameters evaluated by method
LIM = abel.Transform(IM,
                     method='linbasex',
                     center='convolution',
                     center_options=dict(square=True),
                     transform_options=dict(basis_dir=None,
                                            proj_angles=proj_angles,
                                            radial_step=radial_step,
                                            smoothing=smoothing,
                                            threshold=threshold,
                                            clip=clip,
                                            return_Beta=True,
                                            verbose=True))

# hansenlaw method - speed and anisotropy parameters evaluated by integration
HIM = abel.Transform(IM,
                     method="hansenlaw",
                     center='convolution',
                     center_options=dict(square=True),
                     angular_integration=True)

# alternative derivation of anisotropy parameters via integration
rrange = [(20, 50), (60, 80), (85, 100), (125, 155), (185, 205), (220, 240)]