Beispiel #1
0
def fourier_integration2DShift(del_f_del_x, delx, del_f_del_y, dely):
    '''
    This function is the direct use of the CONTINOUS formulation of
    Frankot-Chellappa, eq 21 in the article:

    T. Frankot and R. Chellappa
        A Method for Enforcing Integrability in Shape from Shading Algorithms,
        IEEE Transactions On Pattern Analysis And Machine Intelligence, Vol 10,
        No 4, Jul 1988

    In addition, it uses the CONTINOUS shift property to avoid singularities
    at zero frequencies

    '''

    fx, fy = np.meshgrid(np.fft.fftfreq(del_f_del_x.shape[1], delx),
                         np.fft.fftfreq(del_f_del_x.shape[0], dely))

    xx, yy = wpu.realcoordmatrix(del_f_del_x.shape[1], delx,
                                 del_f_del_x.shape[0], dely)

    fo_x = -np.abs(fx[0, 1] / 15)  # shift fx value
    fo_y = -np.abs(fy[1, 0] / 15)  # shift fy value

    phaseShift = np.exp(2 * np.pi * 1j *
                        (fo_x * xx + fo_y * yy))  # exp factor for shift

    mult_factor = 1 / (2 * np.pi * 1j) / (fx - fo_x - 1j * fy + 1j * fo_y)

    bigGprime = fft2((del_f_del_x - 1j * del_f_del_y) * phaseShift)
    bigG = bigGprime * mult_factor

    func_g = ifft2(bigG) / phaseShift

    func_g -= np.min(
        np.real(func_g))  # since the integral have and undefined constant,
    # here it is applied an arbritary offset

    return func_g
dpc_x = np.array(fh5['dpcHorizontal'])
dpc_y = np.array(fh5['dpcVertical'])


phase = np.array(fh5['phase'])



# =============================================================================
# %% parameters
# =============================================================================

size = np.shape(dpc_x)
pixelsize = .650*1e-6
xx, yy = wpu.realcoordmatrix(size[1], pixelsize, size[0], pixelsize)



#==============================================================================
# %% Integration
#==============================================================================


from wavepy.surface_from_grad import frankotchellappa, error_integration

result = frankotchellappa(dpc_x, dpc_y, reflec_pad=True)

result = np.real(result)

result *= -1
                            title='Dark Field',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize) * 1e6)

    # %% DPC

    dpc_1d = unwrap_phase(dpc_1d)
    wpu.plot_slide_colorbar(dpc_1d / np.pi / 2.0,
                            title=r'DPC [$\pi rad$]',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize) * 1e6)

    # %%
    xx, yy = wpu.realcoordmatrix(dpc_1d.shape[1], pixelSize, dpc_1d.shape[0],
                                 pixelSize)
    wpu.plot_profile(xx * 1e3,
                     yy * 1e3,
                     dpc_1d / np.pi / 2.0,
                     xlabel='[mm]',
                     ylabel='[mm]')

    # %% chi2

    plt.figure()
    hist = plt.hist(chi2[np.where(chi2 < 10 * np.std(chi2))], 100, log=False)
    plt.title(r'$\chi^2$', fontsize=14, weight='bold')
    plt.show(block=False)

    chi2_copy = np.copy(chi2)
Beispiel #4
0
    data_dir = fname.rsplit('/', 1)[0]
    print(fname)
    print(data_dir)
    os.chdir(data_dir)
    os.makedirs('residuals', exist_ok=True)
    os.chdir('residuals')

    wpu.log_this(preffname=fname.split('.')[0].split('/')[-1] + '_fit',
                 inifname=inifname)

    # %% Load Input File

    if fname.split('.')[-1] == 'sdf':
        thickness, pixelSize, headerdic = wpu.load_sdf_file(fname)
        xx, yy = wpu.realcoordmatrix(thickness.shape[1], pixelSize[1],
                                     thickness.shape[0], pixelSize[0])

    elif fname.split('.')[-1] == 'pickle':

        thickness, xx, yy = load_pickle_surf(fname, False)

        thickness *= 1e-6
        #            thickness *= -1.0 # minus1 here
        xx *= 1e-6
        yy *= 1e-6
        pixelSize = [np.mean(np.diff(xx[0, :])), np.mean(np.diff(yy[:, 0]))]

    else:
        wpu.print_red('ERROR: Wrong file type!')
        exit(-1)
Beispiel #5
0
norm_abs_fftimg = abs_fftimg / np.nanmax(abs_fftimg)

img2 = np.log(norm_abs_fftimg + 1e-10)

# %% Rotation in the Reciprocal space

img_rotated, angle = wpu.rotate_img_graphical(img2, mode='edge')

norm_abs_fftimg = skimage.transform.rotate(norm_abs_fftimg,
                                           -angle,
                                           mode='edge')

# %% x and y axes

qx, qy = wpu.realcoordmatrix(img_rotated.shape[1],
                             pixelsize / dist2detector * kwave,
                             img_rotated.shape[0],
                             pixelsize / dist2detector * kwave)

rho_x, rho_y = wpu.reciprocalcoordmatrix(qx.shape[1], qy[1, 0] - qy[0, 0],
                                         qy.shape[0], qx[0, 1] - qx[0, 0])

rho_x *= 2 * np.pi
rho_y *= 2 * np.pi

# %%

#plotThis = norm_abs_fftimg # *wpu.nan_mask_threshold(norm_abs_fftimg,1e-2*1j)
#plotThis = scipy.ndimage.uniform_filter(norm_abs_fftimg, size=(1,1))

plotThis = scipy.ndimage.uniform_filter(norm_abs_fftimg, size=(1, 1))
plotThis[plotThis >= .01] = 0.0
Beispiel #6
0
def error_integration(delx_f, delx_y, func,
                      pixelsize, errors=False,
                      shifthalfpixel=False, plot_flag=True):

    func = np.real(func)

    if shifthalfpixel:
        func = wpu.shift_subpixel_2d(func, 2)

    xx, yy = wpu.realcoordmatrix(func.shape[1], pixelsize[1],
                                 func.shape[0], pixelsize[0])
    midleX = xx.shape[0] // 2
    midleY = xx.shape[1] // 2

    grad_x, grad_y = _grad(func)

    grad_x -= np.mean(grad_x)
    grad_y -= np.mean(grad_y)
    delx_f -= np.mean(delx_f)
    delx_y -= np.mean(delx_y)

    amp_x = np.max(delx_f) - np.min(delx_f)
    amp_y = np.max(delx_y) - np.min(delx_y)

    error_x = np.abs(grad_x - delx_f)/amp_x*100
    error_y = np.abs(grad_y - delx_y)/amp_y*100

    if plot_flag:
        plt.figure(figsize=(14, 10))

        ax1 = plt.subplot(221)
        ax1.ticklabel_format(style='sci', axis='both', scilimits=(0, 1))
        ax1.plot(xx[midleX, :], delx_f[midleX, :], '-kx',
                 markersize=10, label='dx data')
        ax1.plot(xx[midleX, :], grad_x[midleX, :], '-r+',
                 markersize=10, label='dx reconstructed')
        ax1.legend(loc=0)

        ax2 = plt.subplot(223, sharex=ax1)
        ax2.plot(xx[midleX, :],
                 error_x[midleX, :], '-g.', label='error x')
        plt.title(r'$\mu$ = {:.2g}'.format(np.mean(error_x[midleX, :])))
        ax2.legend(loc=0)

        ax3 = plt.subplot(222, sharex=ax1, sharey=ax1)
        ax3.plot(yy[:, midleY], delx_y[:, midleY], '-kx',
                 markersize=10, label='dy data')
        ax3.plot(yy[:, midleY], grad_y[:, midleY], '-r+',
                 markersize=10, label='dy reconstructed')
        ax3.legend(loc=0)

        ax4 = plt.subplot(224, sharex=ax1, sharey=ax2)
        ax4.plot(yy[:, midleY],
                 error_y[:, midleY], '-g.', label='error y')
        plt.title(r'$\mu$ = {:.2g}'.format(np.mean(error_y[:, midleY])))
        ax4.legend(loc=0)

        plt.suptitle('Error integration', fontsize=22)
        plt.show(block=False)

    if errors:
        return error_x, error_y
Beispiel #7
0
import numpy as np
import matplotlib.pyplot as plt
import wavepy.utils as wpu





# =============================================================================
# %% parameters
# =============================================================================

size = (501,491)
pixelsize = .0093085684600
xx, yy = wpu.realcoordmatrix(size[1], pixelsize, size[0], pixelsize)



#===============================================================================
# %% Functions
#===============================================================================

parab_waved =  -xx**2/.2 -yy**2/.3 + 0.5*np.cos(100*np.sqrt(xx**2+yy**2))

fermidirac = 1.0/(1 + np.exp((np.sqrt(xx**2+yy**2/.5)-1.1)/.1))

xo = -2
yo = -3.54356
trigfunc = 5*np.sin((xx-xo)+(yy-yo)) + 2*np.sin((xx-xo)*6*(yy-yo)) + \
            np.sin((xx-xo)*5) + .5*np.sin((xx-xo)**2*5)
Beispiel #8
0

# %%

pixelsize = .1e-6
dist2detector = 450e-3
phenergy = 778.00

wavelength = hc / phenergy
kwave = 2 * np.pi / wavelength

# %% Make the mask
positions_x = np.array([-22.5, -7.5, -1.5, 0, 3, 12, 0, 0, 0, 0, 0]) * 1e-6
positions_y = np.array([0, 0, 0, 0, 0, 0, -22.5, -7.5, -1.5, 3, 12]) * 1e-6

xx, yy = wpu.realcoordmatrix(2001, pixelsize, 2001, pixelsize)

# abs mask
mask_NRA = xx * 0.0

for i in range(positions_x.size):

    xo, yo = positions_x[i], positions_y[i]
    mask_NRA[(np.sqrt((xx - xo)**2 + (yy - yo)**2) < .50000000e-6)] += 1.0

# phase mask
#mask_NRA = xx*0.0*1j + 1.0
#
#for i in range(positions_x.size):
#
#    xo, yo = positions_x[i], positions_y[i]
    wpu.plot_slide_colorbar(dk_field, title='Dark Field',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize)*1e6)

    # %% DPC

    dpc_1d = unwrap_phase(dpc_1d)
    wpu.plot_slide_colorbar(dpc_1d/np.pi/2.0,
                            title=r'DPC [$\pi rad$]',
                            xlabel=r'x [$\mu m$]',
                            ylabel=r'y [$\mu m$]',
                            extent=wpu.extent_func(dpc_1d, pixelSize)*1e6)

    # %%
    xx, yy = wpu.realcoordmatrix(dpc_1d.shape[1], pixelSize,
                                 dpc_1d.shape[0], pixelSize)
    wpu.plot_profile(xx*1e3, yy*1e3, dpc_1d/np.pi/2.0,
                     xlabel='[mm]', ylabel='[mm]')

    # %% chi2

    plt.figure()
    hist = plt.hist(chi2[np.where(chi2 < 10*np.std(chi2))], 100, log=False)
    plt.title(r'$\chi^2$', fontsize=14, weight='bold')
    plt.show(block=False)

    chi2_copy = np.copy(chi2)

    wpu.plot_slide_colorbar(chi2_copy, title=r'$\chi^2$ sample',
                            xlabel=r'x [$\mu m$ ]',
                            ylabel=r'y [$\mu m$ ]',
Beispiel #10
0
    ylabel = figx.axes[0].images[0].axes.properties()['ylabel']
    cmap = figx.axes[0].images[0].properties()['cmap'].name

    [[vmin, vmax], cmap] = wpu.plot_slide_colorbar(data,
                                                   title=title,
                                                   xlabel=xlabel,
                                                   ylabel=ylabel,
                                                   extent=[xi, xf, yi, yf])

    # plot surface
    fig = plt.figure(figsize=(10, 8))
    ax = fig.add_subplot(111, projection='3d')

    pixelsize = [(xf - xi) / data.shape[1], (yf - yi) / data.shape[0]]

    wpu.realcoordmatrix()

    xxGrid, yyGrid = np.meshgrid(np.linspace(xi, xf, data.shape[1]),
                                 np.linspace(yi, yf, data.shape[0]),
                                 indexing='xy')

    if np.all(np.isfinite(data)):
        surf = ax.plot_surface(xxGrid,
                               yyGrid,
                               data,
                               vmin=vmin,
                               vmax=vmax,
                               rstride=data.shape[0] // 101 + 1,
                               cstride=data.shape[1] // 101 + 1,
                               cmap=cmap,
                               linewidth=.3,
Beispiel #11
0
#==============================================================================
# %% Crop ROI
#==============================================================================

#idx4crop = [635, 1993, 841, 1792]
#img = wpu.crop_matrix_at_indexes(spe_file.data[0], idx4crop)

img, idx4crop = wpu.crop_graphic_image(spe_file.data[0], verbose=False)
print(idx4crop)

img = wpu.pad_to_make_square(img, mode='edge')

# %% Plot Detector coordinates

xx, yy = wpu.realcoordmatrix(img.shape[1], pixelsize, img.shape[0], pixelsize)

plt.figure(figsize=plt.figaspect(.6))
plt.contourf(xx * 1e3,
             yy * 1e3,
             img / np.nanmax(img),
             201,
             cmap='plasma',
             vmin=0.1)
plt.xlabel(r'$x$ [mm]')
plt.ylabel(r'$y$ [mm]')
plt.title(r'Data ')
plt.colorbar()
plt.show(block=True)

#xVec = wpu.realcoordvec(img.shape[1], pixelsize)