예제 #1
0
def plot_DPC(dpc01,
             dpc10,
             pixelsize,
             titleStr='',
             saveFigFlag=False,
             saveFileSuf='graph'):
    '''
    TODO: Write Docstring
    Plot differencial phase signal
    '''
    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(dpc01.size) * pixelsize[0])

    dpc01_plot = dpc01 * pixelsize[1] / np.pi
    dpc10_plot = dpc10 * pixelsize[0] / np.pi

    vlim01 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc01_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc01_plot, 5))))
    vlim10 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc10_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc10_plot, 5))))

    plt.figure(figsize=(12, 6))
    plt.subplot(121)
    plt.imshow(dpc01_plot,
               cmap='RdGy_r',
               vmin=-vlim01,
               vmax=vlim01,
               extent=wpu.extent_func(dpc01_plot, pixelsize) * factor)

    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(dpc10_plot,
               cmap='RdGy_r',
               vmin=-vlim10,
               vmax=vlim10,
               extent=wpu.extent_func(dpc10_plot, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Vertical', fontsize=18, weight='bold')

    plt.suptitle('Differential Phase ' + r'[$\pi$ rad]' + titleStr,
                 fontsize=18,
                 weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #2
0
def plot_intensities_harms(int00,
                           int01,
                           int10,
                           pixelsize,
                           titleStr,
                           saveFigFlag=False,
                           saveFileSuf='graph'):
    # Plot Real image (intensity)

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(int00.size) * pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(131)
    plt.imshow(int00,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int00, 4),
               extent=wpu.extent_func(int00, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('00', fontsize=18, weight='bold')

    plt.subplot(132)
    plt.imshow(int01,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int01, 4),
               extent=wpu.extent_func(int01, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('01', fontsize=18, weight='bold')

    plt.subplot(133)
    plt.imshow(int10,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int10, 4),
               extent=wpu.extent_func(int10, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('10', fontsize=18, weight='bold')

    plt.suptitle('Absorption obtained from the Harmonics' + titleStr,
                 fontsize=18,
                 weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #3
0
def plot_DPC(dpc01, dpc10,
             pixelsize, titleStr='',
             saveFigFlag=False, saveFileSuf='graph'):
    '''
    TODO: Write Docstring
    Plot differencial phase signal
    '''
    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(dpc01.size)*pixelsize[0])

    dpc01_plot = dpc01*pixelsize[1]/np.pi
    dpc10_plot = dpc10*pixelsize[0]/np.pi

    vlim01 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc01_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc01_plot, 5))))
    vlim10 = np.max((np.abs(wpu.mean_plus_n_sigma(dpc10_plot, -5)),
                     np.abs(wpu.mean_plus_n_sigma(dpc10_plot, 5))))

    plt.figure(figsize=(12, 6))
    plt.subplot(121)
    plt.imshow(dpc01_plot, cmap='RdGy_r',
               vmin=-vlim01, vmax=vlim01,
               extent=wpu.extent_func(dpc01_plot, pixelsize)*factor)

    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(dpc10_plot, cmap='RdGy_r',
               vmin=-vlim10, vmax=vlim10,
               extent=wpu.extent_func(dpc10_plot, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('DPC - Vertical', fontsize=18,
              weight='bold')

    plt.suptitle('Differential Phase ' + r'[$\pi$ rad]' + titleStr,
                 fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
def _default_plot_for_pickle(data, pixelsize, patternforpickle='graph',
                             title='', xlabel=r'$x$', ylabel=r'$y$', ctitle='',
                             removeSpark=True, cmap='viridis'):

    if removeSpark:
        vmin = wpu.mean_plus_n_sigma(data, -6)
        vmax = wpu.mean_plus_n_sigma(data, 6)
    else:
        vmin = np.min(data)
        vmax = np.max(data)

    #    vmax = np.max((np.abs(vmin), np.abs(vmax)))
    #    vmin = -vmax

    fig = plt.figure(figsize=(12, 9.5))

    plt.imshow(data,
               extent=wpu.extent_func(data, pixelsize)*1e6,
               cmap=cmap, vmin=vmin, vmax=vmax)

    plt.xlabel(xlabel, fontsize=24)
    plt.ylabel(ylabel, fontsize=24)

    cbar = plt.colorbar(shrink=0.9)
    cbar.ax.set_title(ctitle, y=1.01)

    plt.title(title, fontsize=24, weight='bold', y=1.01)

    wpu.save_figs_with_idx_pickle(fig, patternforpickle)

    plt.show(block=True)
예제 #5
0
def plot_intensities_harms(int00, int01, int10,
                           pixelsize, titleStr,
                           saveFigFlag=False, saveFileSuf='graph'):
    # Plot Real image (intensity)

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(int00.size)*pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(131)
    plt.imshow(int00, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int00, 4),
               extent=wpu.extent_func(int00, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('00', fontsize=18, weight='bold')

    plt.subplot(132)
    plt.imshow(int01, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int01, 4),
               extent=wpu.extent_func(int01, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('01', fontsize=18, weight='bold')

    plt.subplot(133)
    plt.imshow(int10, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(int10, 4),
               extent=wpu.extent_func(int10, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('10', fontsize=18, weight='bold')

    plt.suptitle('Absorption obtained from the Harmonics' + titleStr,
                 fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #6
0
def plot_dark_field(darkField01,
                    darkField10,
                    pixelsize,
                    titleStr='',
                    saveFigFlag=False,
                    saveFileSuf='graph'):
    '''
    TODO: Write Docstring

    Plot Dark field

    '''

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(darkField01.size) * pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(121)
    plt.imshow(darkField01,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField01, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(darkField10,
               cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField10, pixelsize) * factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Vertical', fontsize=18, weight='bold')  # 10

    plt.suptitle('Dark Field', fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
예제 #7
0
def plot_dark_field(darkField01, darkField10,
                    pixelsize, titleStr='',
                    saveFigFlag=False, saveFileSuf='graph'):
    '''
    TODO: Write Docstring

    Plot Dark field

    '''

    if titleStr is not '':
        titleStr = ', ' + titleStr

    factor, unit_xy = wpu.choose_unit(np.sqrt(darkField01.size)*pixelsize[0])

    plt.figure(figsize=(14, 6))

    plt.subplot(121)
    plt.imshow(darkField01, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField01, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Horizontal', fontsize=18, weight='bold')  # 01

    plt.subplot(122)
    plt.imshow(darkField10, cmap='viridis',
               vmax=wpu.mean_plus_n_sigma(darkField01, 4),
               extent=wpu.extent_func(darkField10, pixelsize)*factor)
    plt.xlabel(r'$[{0} m]$'.format(unit_xy))
    plt.ylabel(r'$[{0} m]$'.format(unit_xy))
    plt.colorbar(shrink=0.5)
    plt.title('Vertical', fontsize=18, weight='bold')  # 10

    plt.suptitle('Dark Field', fontsize=18, weight='bold')

    plt.tight_layout(rect=[0, 0, 1, 1])
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)
    plt.show(block=False)
def main_single_gr_Talbot(img, imgRef,
                          phenergy, pixelsize, distDet2sample,
                          period_harm, saveFileSuf,
                          unwrapFlag=True,
                          plotFlag=True,
                          saveFigFlag=False):

    global inifname  # name of .ini file

    [period_harm_Vert, period_harm_Hor] = period_harm


    #    img, imgRef = wpu.align_two_images(img, imgRef)

    # Crop

    img_size_o = np.shape(img)

    # take index from ini file
    idx4crop = list(map(int, (wpu.get_from_ini_file(inifname, 'Parameters',
                                                    'Crop').split(','))))

    # Plot Real Image wiht default crop

    tmpImage = wpu.crop_matrix_at_indexes(img, idx4crop)

    plt.figure()
    plt.imshow(tmpImage,
               cmap='viridis',
               extent=wpu.extent_func(tmpImage, pixelsize)*1e6)
    plt.xlabel(r'$[\mu m]$')
    plt.ylabel(r'$[\mu m]$')
    plt.colorbar()

    plt.title('Raw Image with initial Crop', fontsize=18, weight='bold')

    plt.pause(.1)
    # ask if the crop need to be changed
    newCrop = easyqt.get_yes_or_no('New Crop?')

    if saveFigFlag and not newCrop:
        wpu.save_figs_with_idx(saveFileSuf + '_Talbot_image')
    plt.close(plt.gcf())

    if newCrop:

        [colorlimit,
         cmap] = wpu.plot_slide_colorbar(img,
                                         title='SELECT COLOR SCALE,\n' +
                                         'Raw Image, No Crop',
                                         xlabel=r'x [$\mu m$ ]',
                                         ylabel=r'y [$\mu m$ ]',
                                         extent=wpu.extent_func(img,
                                                                pixelsize)*1e6)

        idx4crop = wpu.graphical_roi_idx(img, verbose=True,
                                         kargs4graph={'cmap': cmap,
                                                      'vmin': colorlimit[0],
                                                      'vmax': colorlimit[1]})
        wpu.set_at_ini_file(inifname, 'Parameters', 'Crop',
                            '{}, {}, {}, {}'.format(idx4crop[0], idx4crop[1],
                                                    idx4crop[2], idx4crop[3]))

        img = wpu.crop_matrix_at_indexes(img, idx4crop)

        # Plot Real Image AFTER crop

        plt.imshow(img, cmap='viridis',
                   extent=wpu.extent_func(img, pixelsize)*1e6)
        plt.xlabel(r'$[\mu m]$')
        plt.ylabel(r'$[\mu m]$')
        plt.colorbar()
        plt.title('Raw Image with New Crop', fontsize=18, weight='bold')

        if saveFigFlag:
            wpu.save_figs_with_idx(saveFileSuf + '_Talbot_image')
        plt.show(block=True)

    else:
        img = tmpImage

    imgRef = wpu.crop_matrix_at_indexes(imgRef, idx4crop)

    # calculate harmonic position after crop

    period_harm_Vert = int(period_harm_Vert*(idx4crop[1] - idx4crop[0]) /
                           img_size_o[0])
    period_harm_Hor = int(period_harm_Hor*(idx4crop[3] - idx4crop[2]) /
                          img_size_o[1])

    # Obtain harmonic periods from images

    (period_harm_Vert,
     _) = wgi.exp_harm_period(img, [period_harm_Vert,
                                    period_harm_Hor],
                                    harmonic_ij=['1', '0'],
                                    searchRegion=20,
                                    isFFT=False, verbose=True)

    (_,
     period_harm_Horz) = wgi.exp_harm_period(img, [period_harm_Vert,
                                             period_harm_Hor],
                                             harmonic_ij=['0', '1'],
                                             searchRegion=20,
                                             isFFT=False, verbose=True)

    # Calculate everything

    harmPeriod = [period_harm_Vert, period_harm_Hor]

    [int00, int01, int10,
     darkField01, darkField10,
     phaseFFT_01,
     phaseFFT_10] = wgi.single_2Dgrating_analyses(img, imgRef,
                                                  harmonicPeriod=harmPeriod,
                                                  plotFlag=plotFlag,
                                                  unwrapFlag=unwrapFlag,
                                                  verbose=True)

    virtual_pixelsize = [0, 0]
    virtual_pixelsize[0] = pixelsize[0]*img.shape[0]/int00.shape[0]
    virtual_pixelsize[1] = pixelsize[1]*img.shape[1]/int00.shape[1]

    diffPhase01 = phaseFFT_01*virtual_pixelsize[1]/distDet2sample/hc*phenergy
    diffPhase10 = phaseFFT_10*virtual_pixelsize[0]/distDet2sample/hc*phenergy

    return [int00, int01, int10,
            darkField01, darkField10,
            diffPhase01, diffPhase10,
            virtual_pixelsize]
예제 #9
0
def extract_harmonic(img, harmonicPeriod,
                     harmonic_ij='00', searchRegion=10, isFFT=False,
                     plotFlag=False, verbose=True):

    """
    Function to extract one harmonic image of the FFT of single grating
    Talbot imaging.


    The function use the provided value of period to search for the harmonics
    peak. The search is done in a rectangle of size
    ``periodVert*periodHor/searchRegion**2``. The final result is a rectagle of
    size ``periodVert x periodHor`` centered at
    ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)``


    Parameters
    ----------

    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : list of integers in the format [periodVert, periodHor]
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image. For 1D grating, set one of the values to negative or
        zero (it will set the period to number of rows or colunms).

    harmonic_ij : string or list of string
        string with the harmonic to extract, for instance '00', '01', '10'
        or '11'. In this notation negative harmonics are not allowed.

        Alternativelly, it accepts a list of string
        ``harmonic_ij=[harmonic_Vertical, harmonic_Horizontal]``, for instance
        ``harmonic_ij=['0', '-1']``

        Note that since the original image contain only real numbers (not
        complex), then negative and positive harmonics are symetric
        related to zero.
    isFFT : Boolean
        Flag that tells if the input image ``img`` is in the reciprocal
        (``isFFT=True``) or in the real space (``isFFT=False``)

    searchRegion: int
        search for the peak will be in a region of harmonicPeriod/searchRegion
        around the theoretical peak position

    plotFlag: Boolean
        Flag to plot the image in the reciprocal space and to show the position
        of the found peaked and the limits of the harmonic image

    verbose: Boolean
        verbose flag.


    Returns
    -------
    2D ndarray
        Copped Images of the harmonics ij


    This functions crops a rectagle of size ``periodVert x periodHor`` centered
    at ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)`` from
    the provided FFT image.


    Note
    ----
        * Note that it is the FFT of the image that is required.
        * The search for the peak is only used to print warning messages.

    **Q: Why not the real image??**

    **A:** Because FFT can be time consuming. If we use the real image, it will
    be necessary to run FFT for each harmonic. It is encourage to wrap this
    function within a function that do the FFT, extract the harmonics, and
    return the real space harmonic image.


    See Also
    --------
    :py:func:`wavepy.grating_interferometry.plot_harmonic_grid`

    """

    (nRows, nColumns) = img.shape

    harV = int(harmonic_ij[0])
    harH = int(harmonic_ij[1])

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    if verbose:
            wpu.print_blue("MESSAGE: Extracting harmonic " +
                           harmonic_ij[0] + harmonic_ij[1])
            wpu.print_blue("MESSAGE: Harmonic period " +
                           "Horizontal: {:d} pixels".format(periodHor))
            wpu.print_blue("MESSAGE: Harmonic period " +
                           "Vertical: {:d} pixels".format(periodVert))

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Horizontal 1D Grating")

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Vertical 1D Grating")

    try:
        _check_harmonic_inside_image(harV, harH, nRows, nColumns,
                                     periodVert, periodHor)
    except ValueError:
        raise SystemExit

    if isFFT:
        imgFFT = img
    else:
        imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    intensity = (np.abs(imgFFT))

    #  Estimate harmonic positions
    idxPeak_ij = _idxPeak_ij(harV, harH, nRows, nColumns,
                             periodVert, periodHor)

    del_i, del_j = _error_harmonic_peak(imgFFT, harV, harH,
                                        periodVert, periodHor,
                                        searchRegion)

    if verbose:
        print("MESSAGE: extract_harmonic:" +
              " harmonic peak " + harmonic_ij[0] + harmonic_ij[1] +
              " is misplaced by:")
        print("MESSAGE: {:d} pixels in vertical, {:d} pixels in hor".format(
               del_i, del_j))

        print("MESSAGE: Theoretical peak index: {:d},{:d} [VxH]".format(
              idxPeak_ij[0], idxPeak_ij[1]))

    if ((np.abs(del_i) > searchRegion // 2) or
       (np.abs(del_j) > searchRegion // 2)):

        wpu.print_red("ATTENTION: Harmonic Peak " + harmonic_ij[0] +
                      harmonic_ij[1] + " is too far from theoretical value.")
        wpu.print_red("ATTENTION: {:d} pixels in vertical,".format(del_i) +
                      "{:d} pixels in hor".format(del_j))

    if plotFlag:

        from matplotlib.patches import Rectangle
        plt.figure(figsize=(8, 7))
        plt.imshow(np.log10(intensity), cmap='inferno', extent=wpu.extent_func(intensity))

        plt.xlabel('Pixels')
        plt.ylabel('Pixels')

        xo = idxPeak_ij[1] - nColumns//2 - periodHor//2
        yo = nRows//2 - idxPeak_ij[0] - periodVert//2
        # xo yo are the lower left position of the reangle

        plt.gca().add_patch(Rectangle((xo, yo),
                                      periodHor, periodVert,
                                      lw=2, ls='--', color='red',
                                      fill=None, alpha=1))

        plt.title('Selected Region ' + harmonic_ij[0] + harmonic_ij[1],
                  fontsize=18, weight='bold')
        plt.show(block=False)

    return imgFFT[idxPeak_ij[0] - periodVert//2:
                  idxPeak_ij[0] + periodVert//2,
                  idxPeak_ij[1] - periodHor//2:
                  idxPeak_ij[1] + periodHor//2]
예제 #10
0
def single_grating_harmonic_images(img,
                                   harmonicPeriod,
                                   searchRegion=10,
                                   plotFlag=False,
                                   verbose=False):
    """
    Auxiliary function to process the data of single 2D grating Talbot imaging.
    It obtain the (real space) harmonic images  00, 01 and 10.

    Parameters
    ----------
    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : list of integers in the format [periodVert, periodHor]
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image. For 1D grating, set one of the values to negative or
        zero (it will set the period to number of rows or colunms).

    searchRegion: int
        search for the peak will be in a region of harmonicPeriod/searchRegion
        around the theoretical peak position. See also
        `:py:func:`wavepy.grating_interferometry.plot_harmonic_grid`

    plotFlag: boolean
        Flag to plot the image in the reciprocal space and to show the position
        of the found peaked and the limits of the harmonic image

    verbose: Boolean
        verbose flag.

    Returns
    -------
    three 2D ndarray data
        Images obtained from the harmonics 00, 01 and 10.

    """

    imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    if plotFlag:
        plot_harmonic_grid(imgFFT, harmonicPeriod=harmonicPeriod, isFFT=True)
        plt.show(block=False)

    imgFFT00 = extract_harmonic(imgFFT,
                                harmonicPeriod=harmonicPeriod,
                                harmonic_ij='00',
                                searchRegion=searchRegion,
                                isFFT=True,
                                plotFlag=plotFlag,
                                verbose=verbose)

    imgFFT01 = extract_harmonic(imgFFT,
                                harmonicPeriod=harmonicPeriod,
                                harmonic_ij=['0', '1'],
                                searchRegion=searchRegion,
                                isFFT=True,
                                plotFlag=plotFlag,
                                verbose=verbose)

    imgFFT10 = extract_harmonic(imgFFT,
                                harmonicPeriod=harmonicPeriod,
                                harmonic_ij=['1', '0'],
                                searchRegion=searchRegion,
                                isFFT=True,
                                plotFlag=plotFlag,
                                verbose=verbose)

    #  Plot Fourier image (intensity)
    if plotFlag:

        # Intensity is Fourier Space
        intFFT00 = np.log10(np.abs(imgFFT00))
        intFFT01 = np.log10(np.abs(imgFFT01))
        intFFT10 = np.log10(np.abs(imgFFT10))

        fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(14, 5))

        for dat, ax, textTitle in zip([intFFT00, intFFT01, intFFT10],
                                      axes.flat,
                                      ['FFT 00', 'FFT 01', 'FFT 10']):

            # The vmin and vmax arguments specify the color limits
            im = ax.imshow(dat,
                           cmap='inferno',
                           vmin=np.min(intFFT00),
                           vmax=np.max(intFFT00),
                           extent=wpu.extent_func(dat))

            ax.set_title(textTitle)
            if textTitle == 'FFT 00':
                ax.set_ylabel('Pixels')

            ax.set_xlabel('Pixels')

        # Make an axis for the colorbar on the right side
        cax = fig.add_axes([0.92, 0.1, 0.03, 0.8])
        fig.colorbar(im, cax=cax)
        plt.suptitle('FFT subsets - Intensity', fontsize=18, weight='bold')
        plt.show(block=False)

    img00 = ifft2(np.fft.ifftshift(imgFFT00), norm='ortho')

    # non existing harmonics will return NAN, so here we check NAN
    if np.all(np.isfinite(imgFFT01)):
        img01 = ifft2(np.fft.ifftshift(imgFFT01), norm='ortho')
    else:
        img01 = imgFFT01

    if np.all(np.isfinite(imgFFT10)):
        img10 = ifft2(np.fft.ifftshift(imgFFT10), norm='ortho')
    else:
        img10 = imgFFT10

    return (img00, img01, img10)
예제 #11
0
def plot_harmonic_grid(img, harmonicPeriod=None, isFFT=False):
    """
    Takes the FFT of single 2D grating Talbot imaging and plot the grid from
    where we extract the harmonic in a image of the



    Parameters
    ----------
    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : integer or list of integers
        If list, it must be in the format ``[periodVert, periodHor]``. If
        integer, then [periodVert = periodHor``.
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        ``periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image``

    isFFT : Boolean
        Flag that tells if the input image ``img`` is in the reciprocal
        (``isFFT=True``) or in the real space (``isFFT=False``)

    """

    if not isFFT:
        imgFFT = np.fft.fftshift(fft2(np.fft.fftshift(img), norm='ortho'))
    else:
        imgFFT = img

    (nRows, nColumns) = imgFFT.shape

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns

    plt.figure(figsize=(8, 7))
    plt.imshow(np.log10(np.abs(imgFFT)),
               cmap='inferno',
               extent=wpu.extent_func(imgFFT))

    plt.xlabel('Pixels')
    plt.ylabel('Pixels')

    harV_min = -(nRows + 1) // 2 // periodVert
    harV_max = (nRows + 1) // 2 // periodVert

    harH_min = -(nColumns + 1) // 2 // periodHor
    harH_max = (nColumns + 1) // 2 // periodHor

    for harV in range(harV_min + 1, harV_max + 2):

        idxPeak_ij = _idxPeak_ij(harV, 0, nRows, nColumns, periodVert,
                                 periodHor)

        plt.axhline(idxPeak_ij[0] - periodVert // 2 - nRows // 2,
                    lw=2,
                    color='r')

    for harH in range(harH_min + 1, harH_max + 2):

        idxPeak_ij = _idxPeak_ij(0, harH, nRows, nColumns, periodVert,
                                 periodHor)
        plt.axvline(idxPeak_ij[1] - periodHor // 2 - nColumns // 2,
                    lw=2,
                    color='r')

    for harV in range(harV_min, harV_max + 1):
        for harH in range(harH_min, harH_max + 1):

            idxPeak_ij = _idxPeak_ij(harV, harH, nRows, nColumns, periodVert,
                                     periodHor)

            plt.plot(idxPeak_ij[1] - nColumns // 2,
                     idxPeak_ij[0] - nRows // 2,
                     'ko',
                     mew=2,
                     mfc="None",
                     ms=15)

            plt.annotate('{:d}{:d}'.format(-harV, harH), (
                idxPeak_ij[1] - nColumns // 2,
                idxPeak_ij[0] - nRows // 2,
            ),
                         color='red',
                         fontsize=20)

    plt.xlim(-nColumns // 2, nColumns - nColumns // 2)
    plt.ylim(-nRows // 2, nRows - nRows // 2)
    plt.title('log scale FFT magnitude, Hamonics Subsets and Indexes',
              fontsize=16,
              weight='bold')
예제 #12
0
def extract_harmonic(img,
                     harmonicPeriod,
                     harmonic_ij='00',
                     searchRegion=10,
                     isFFT=False,
                     plotFlag=False,
                     verbose=True):
    """
    Function to extract one harmonic image of the FFT of single grating
    Talbot imaging.


    The function use the provided value of period to search for the harmonics
    peak. The search is done in a rectangle of size
    ``periodVert*periodHor/searchRegion**2``. The final result is a rectagle of
    size ``periodVert x periodHor`` centered at
    ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)``


    Parameters
    ----------

    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : list of integers in the format [periodVert, periodHor]
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image. For 1D grating, set one of the values to negative or
        zero (it will set the period to number of rows or colunms).

    harmonic_ij : string or list of string
        string with the harmonic to extract, for instance '00', '01', '10'
        or '11'. In this notation negative harmonics are not allowed.

        Alternativelly, it accepts a list of string
        ``harmonic_ij=[harmonic_Vertical, harmonic_Horizontal]``, for instance
        ``harmonic_ij=['0', '-1']``

        Note that since the original image contain only real numbers (not
        complex), then negative and positive harmonics are symetric
        related to zero.
    isFFT : Boolean
        Flag that tells if the input image ``img`` is in the reciprocal
        (``isFFT=True``) or in the real space (``isFFT=False``)

    searchRegion: int
        search for the peak will be in a region of harmonicPeriod/searchRegion
        around the theoretical peak position

    plotFlag: Boolean
        Flag to plot the image in the reciprocal space and to show the position
        of the found peaked and the limits of the harmonic image

    verbose: Boolean
        verbose flag.


    Returns
    -------
    2D ndarray
        Copped Images of the harmonics ij


    This functions crops a rectagle of size ``periodVert x periodHor`` centered
    at ``(harmonic_Vertical*periodVert x harmonic_Horizontal*periodHor)`` from
    the provided FFT image.


    Note
    ----
        * Note that it is the FFT of the image that is required.
        * The search for the peak is only used to print warning messages.

    **Q: Why not the real image??**

    **A:** Because FFT can be time consuming. If we use the real image, it will
    be necessary to run FFT for each harmonic. It is encourage to wrap this
    function within a function that do the FFT, extract the harmonics, and
    return the real space harmonic image.


    See Also
    --------
    :py:func:`wavepy.grating_interferometry.plot_harmonic_grid`

    """

    (nRows, nColumns) = img.shape

    harV = int(harmonic_ij[0])
    harH = int(harmonic_ij[1])

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    if verbose:
        wpu.print_blue("MESSAGE: Extracting harmonic " + harmonic_ij[0] +
                       harmonic_ij[1])
        wpu.print_blue("MESSAGE: Harmonic period " +
                       "Horizontal: {:d} pixels".format(periodHor))
        wpu.print_blue("MESSAGE: Harmonic period " +
                       "Vertical: {:d} pixels".format(periodVert))

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Horizontal 1D Grating")

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns
        if verbose:
            wpu.print_blue("MESSAGE: Assuming Vertical 1D Grating")

    try:
        _check_harmonic_inside_image(harV, harH, nRows, nColumns, periodVert,
                                     periodHor)
    except ValueError:
        raise SystemExit

    if isFFT:
        imgFFT = img
    else:
        imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    intensity = (np.abs(imgFFT))

    #  Estimate harmonic positions
    idxPeak_ij = _idxPeak_ij(harV, harH, nRows, nColumns, periodVert,
                             periodHor)

    del_i, del_j = _error_harmonic_peak(imgFFT, harV, harH, periodVert,
                                        periodHor, searchRegion)

    if verbose:
        print("MESSAGE: extract_harmonic:" + " harmonic peak " +
              harmonic_ij[0] + harmonic_ij[1] + " is misplaced by:")
        print("MESSAGE: {:d} pixels in vertical, {:d} pixels in hor".format(
            del_i, del_j))

        print("MESSAGE: Theoretical peak index: {:d},{:d} [VxH]".format(
            idxPeak_ij[0], idxPeak_ij[1]))

    if ((np.abs(del_i) > searchRegion // 2)
            or (np.abs(del_j) > searchRegion // 2)):

        wpu.print_red("ATTENTION: Harmonic Peak " + harmonic_ij[0] +
                      harmonic_ij[1] + " is too far from theoretical value.")
        wpu.print_red("ATTENTION: {:d} pixels in vertical,".format(del_i) +
                      "{:d} pixels in hor".format(del_j))

    if plotFlag:

        from matplotlib.patches import Rectangle
        plt.figure(figsize=(8, 7))
        plt.imshow(np.log10(intensity),
                   cmap='inferno',
                   extent=wpu.extent_func(intensity))

        plt.xlabel('Pixels')
        plt.ylabel('Pixels')

        xo = idxPeak_ij[1] - nColumns // 2 - periodHor // 2
        yo = nRows // 2 - idxPeak_ij[0] - periodVert // 2
        # xo yo are the lower left position of the reangle

        plt.gca().add_patch(
            Rectangle((xo, yo),
                      periodHor,
                      periodVert,
                      lw=2,
                      ls='--',
                      color='red',
                      fill=None,
                      alpha=1))

        plt.title('Selected Region ' + harmonic_ij[0] + harmonic_ij[1],
                  fontsize=18,
                  weight='bold')
        plt.show(block=False)

    return imgFFT[idxPeak_ij[0] - periodVert // 2:idxPeak_ij[0] +
                  periodVert // 2, idxPeak_ij[1] -
                  periodHor // 2:idxPeak_ij[1] + periodHor // 2]
예제 #13
0
def plot_integration(integrated,
                     pixelsize,
                     titleStr='Title',
                     ctitle=' ',
                     max3d_grid_points=101,
                     plotProfile=True,
                     plot3dFlag=True,
                     saveFigFlag=False,
                     saveFileSuf='graph',
                     **kwarg4surf):
    '''
    TODO: Write Docstring
    '''

    xxGrid, yyGrid = wpu.grid_coord(integrated, pixelsize)

    factor_x, unit_x = wpu.choose_unit(xxGrid)
    factor_y, unit_y = wpu.choose_unit(yyGrid)

    # Plot Integration 2

    if plot3dFlag:

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

        rstride = integrated.shape[0] // max3d_grid_points + 1
        cstride = integrated.shape[1] // max3d_grid_points + 1

        surf = ax.plot_surface(xxGrid * factor_x,
                               yyGrid * factor_y,
                               integrated[::-1, :],
                               rstride=rstride,
                               cstride=cstride,
                               cmap='viridis',
                               linewidth=0.1,
                               **kwarg4surf)

        ax_lim = np.max([np.abs(xxGrid * factor_x), np.abs(yyGrid * factor_y)])
        ax.set_xlim3d(-ax_lim, ax_lim)
        ax.set_ylim3d(-ax_lim, ax_lim)

        if 'vmin' in kwarg4surf:
            ax.set_zlim3d(bottom=kwarg4surf['vmin'])
        if 'vmax' in kwarg4surf:
            ax.set_zlim3d(top=kwarg4surf['vmax'])

        plt.xlabel(r'$x [' + unit_x + ' m]$', fontsize=24)
        plt.ylabel(r'$y [' + unit_y + ' m]$', fontsize=24)

        plt.title(titleStr, fontsize=24, weight='bold')
        cbar = plt.colorbar(surf, shrink=.8, aspect=20)
        cbar.ax.set_title(ctitle, y=1.01)

        plt.tight_layout(rect=[0, 0, 1, 1])

        ax.text2D(0.05,
                  0.9,
                  'strides = {}, {}'.format(rstride, cstride),
                  transform=ax.transAxes)

        if saveFigFlag:
            ax.view_init(elev=30, azim=60)
            wpu.save_figs_with_idx(saveFileSuf)
            ax.view_init(elev=30, azim=-120)
            wpu.save_figs_with_idx(saveFileSuf)
            plt.pause(.5)

        plt.show(block=False)

    if plotProfile:
        wpu.plot_profile(xxGrid * factor_x,
                         yyGrid * factor_y,
                         integrated[::-1, :],
                         xlabel=r'$x [' + unit_x + ' m]$',
                         ylabel=r'$y [' + unit_y + ' m]$',
                         title=titleStr,
                         xunit='\mu m',
                         yunit='\mu m',
                         arg4main={
                             'cmap': 'viridis',
                             'lw': 3
                         })

    if saveFigFlag:
        plt.ioff()
        plt.figure(figsize=(10, 8))

        plt.imshow(integrated[::-1, :],
                   cmap='viridis',
                   extent=wpu.extent_func(integrated, pixelsize) * factor_x,
                   **kwarg4surf)

        plt.xlabel(r'$x [' + unit_x + ' m]$', fontsize=24)
        plt.ylabel(r'$y [' + unit_x + ' m]$', fontsize=24)

        plt.title(titleStr, fontsize=18, weight='bold')
        cbar = plt.colorbar()
        cbar.ax.set_title(ctitle, y=1.01)
        wpu.save_figs_with_idx(saveFileSuf)
        plt.close()
        plt.ion()
예제 #14
0
    (list_sample_files, list_ref_files, list_dark_files, pixelSize,
     stepSize) = intial_setup()

    # ==========================================================================
    # % % Load one image and crop
    # ==========================================================================

    img = dxchange.read_tiff(list_sample_files[0])

    [colorlimit, cmap
     ] = wpu.plot_slide_colorbar(img,
                                 title='Raw Image',
                                 xlabel=r'x [$\mu m$ ]',
                                 ylabel=r'y [$\mu m$ ]',
                                 extent=wpu.extent_func(img, pixelSize) * 1e6)

    img_croped, idx4crop = wpu.crop_graphic(zmatrix=img,
                                            verbose=True,
                                            kargs4graph={
                                                'cmap': cmap,
                                                'vmin': colorlimit[0],
                                                'vmax': colorlimit[1]
                                            })

    # ==========================================================================
    # %% Load tiff files to numpy array
    # ==========================================================================

    img_stack, ref_stack = files_to_array(list_sample_files,
                                          list_ref_files,
예제 #15
0
    # ==========================================================================

    (list_sample_files, list_ref_files, list_dark_files,
     pixelSize, stepSize) = intial_setup()

    # ==========================================================================
    # % % Load one image and crop
    # ==========================================================================

    img = dxchange.read_tiff(list_sample_files[0])

    [colorlimit,
     cmap] = wpu.plot_slide_colorbar(img, title='Raw Image',
                                         xlabel=r'x [$\mu m$ ]',
                                         ylabel=r'y [$\mu m$ ]',
                                   extent=wpu.extent_func(img, pixelSize)*1e6)

    img_croped, idx4crop = wpu.crop_graphic(zmatrix=img, verbose=True,
                                            kargs4graph={'cmap': cmap,
                                                         'vmin': colorlimit[0],
                                                         'vmax': colorlimit[1]})


    # ==========================================================================
    # %% Load tiff files to numpy array
    # ==========================================================================

    img_stack, ref_stack = files_to_array(list_sample_files,
                                          list_ref_files,
                                          list_dark_files,
                                          idx4crop=idx4crop)
예제 #16
0
def plot_integration(integrated, pixelsize,
                     titleStr='Title', ctitle=' ',
                     max3d_grid_points=101,
                     plotProfile=True,
                     plot3dFlag=True,
                     saveFigFlag=False,
                     saveFileSuf='graph',
                     **kwarg4surf):
    '''
    TODO: Write Docstring
    '''

    xxGrid, yyGrid = wpu.grid_coord(integrated, pixelsize)

    factor_x, unit_x = wpu.choose_unit(xxGrid)
    factor_y, unit_y = wpu.choose_unit(yyGrid)

    # Plot Integration 2

    if plot3dFlag:

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

        rstride = integrated.shape[0] // max3d_grid_points + 1
        cstride = integrated.shape[1] // max3d_grid_points + 1

        surf = ax.plot_surface(xxGrid*factor_x, yyGrid*factor_y,
                               integrated[::-1, :],
                               rstride=rstride,
                               cstride=cstride,
                               cmap='viridis', linewidth=0.1, **kwarg4surf)

        ax_lim = np.max([np.abs(xxGrid*factor_x), np.abs(yyGrid*factor_y)])
        ax.set_xlim3d(-ax_lim, ax_lim)
        ax.set_ylim3d(-ax_lim, ax_lim)

        if 'vmin' in kwarg4surf:
            ax.set_zlim3d(bottom=kwarg4surf['vmin'])
        if 'vmax' in kwarg4surf:
            ax.set_zlim3d(top=kwarg4surf['vmax'])

        plt.xlabel(r'$x [' + unit_x + ' m]$', fontsize=24)
        plt.ylabel(r'$y [' + unit_y + ' m]$', fontsize=24)

        plt.title(titleStr, fontsize=24, weight='bold')
        cbar = plt.colorbar(surf, shrink=.8, aspect=20)
        cbar.ax.set_title(ctitle, y=1.01)

        plt.tight_layout(rect=[0, 0, 1, 1])

        ax.text2D(0.05, 0.9, 'strides = {}, {}'.format(rstride, cstride),
                    transform=ax.transAxes)

        if saveFigFlag:
            ax.view_init(elev=30, azim=60)
            wpu.save_figs_with_idx(saveFileSuf)
            ax.view_init(elev=30, azim=-120)
            wpu.save_figs_with_idx(saveFileSuf)
            plt.pause(.5)

        plt.show(block=False)

    if plotProfile:
        wpu.plot_profile(xxGrid*factor_x, yyGrid*factor_y,
                         integrated[::-1, :],
                         xlabel=r'$x [' + unit_x + ' m]$',
                         ylabel=r'$y [' + unit_y + ' m]$',
                         title=titleStr,
                         xunit='\mu m', yunit='\mu m',
                         arg4main={'cmap': 'viridis', 'lw': 3})

    if saveFigFlag:
        plt.ioff()
        plt.figure(figsize=(10, 8))

        plt.imshow(integrated[::-1, :], cmap='viridis',
                   extent=wpu.extent_func(integrated, pixelsize)*factor_x,
                   **kwarg4surf)

        plt.xlabel(r'$x [' + unit_x + ' m]$', fontsize=24)
        plt.ylabel(r'$y [' + unit_x + ' m]$', fontsize=24)

        plt.title(titleStr, fontsize=18, weight='bold')
        cbar = plt.colorbar()
        cbar.ax.set_title(ctitle, y=1.01)
        wpu.save_figs_with_idx(saveFileSuf)
        plt.close()
        plt.ion()
예제 #17
0
def plot_harmonic_grid(img, harmonicPeriod=None, isFFT=False):
    """
    Takes the FFT of single 2D grating Talbot imaging and plot the grid from
    where we extract the harmonic in a image of the



    Parameters
    ----------
    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : integer or list of integers
        If list, it must be in the format ``[periodVert, periodHor]``. If
        integer, then [periodVert = periodHor``.
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        ``periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image``

    isFFT : Boolean
        Flag that tells if the input image ``img`` is in the reciprocal
        (``isFFT=True``) or in the real space (``isFFT=False``)

    """

    if not isFFT:
        imgFFT = np.fft.fftshift(fft2(np.fft.fftshift(img),
                                             norm='ortho'))
    else:
        imgFFT = img

    (nRows, nColumns) = imgFFT.shape

    periodVert = harmonicPeriod[0]
    periodHor = harmonicPeriod[1]

    # adjusts for 1D grating
    if periodVert <= 0 or periodVert is None:
        periodVert = nRows

    if periodHor <= 0 or periodHor is None:
        periodHor = nColumns

    plt.figure(figsize=(8, 7))
    plt.imshow(np.log10(np.abs(imgFFT)), cmap='inferno',
               extent=wpu.extent_func(imgFFT))

    plt.xlabel('Pixels')
    plt.ylabel('Pixels')

    harV_min = -(nRows + 1) // 2 // periodVert
    harV_max = (nRows + 1) // 2 // periodVert

    harH_min = -(nColumns + 1) // 2 // periodHor
    harH_max = (nColumns + 1) // 2 // periodHor

    for harV in range(harV_min + 1, harV_max + 2):

        idxPeak_ij = _idxPeak_ij(harV, 0, nRows, nColumns,
                                 periodVert, periodHor)

        plt.axhline(idxPeak_ij[0] - periodVert//2 - nRows//2,
                    lw=2, color='r')

    for harH in range(harH_min + 1, harH_max + 2):

        idxPeak_ij = _idxPeak_ij(0, harH, nRows, nColumns,
                                 periodVert, periodHor)
        plt.axvline(idxPeak_ij[1] - periodHor // 2 - nColumns//2,
                    lw=2, color='r')

    for harV in range(harV_min, harV_max + 1):
        for harH in range(harH_min, harH_max + 1):

            idxPeak_ij = _idxPeak_ij(harV, harH,
                                     nRows, nColumns,
                                     periodVert, periodHor)

            plt.plot(idxPeak_ij[1] - nColumns//2,
                     idxPeak_ij[0] - nRows//2,
                    'ko', mew=2, mfc="None", ms=15)

            plt.annotate('{:d}{:d}'.format(-harV, harH),
                         (idxPeak_ij[1] - nColumns//2,
                          idxPeak_ij[0] - nRows//2,),
                         color='red', fontsize=20)

    plt.xlim(-nColumns//2, nColumns - nColumns//2)
    plt.ylim(-nRows//2, nRows - nRows//2)
    plt.title('log scale FFT magnitude, Hamonics Subsets and Indexes',
              fontsize=16, weight='bold')
def main():
    wpu._mpl_settings_4_nice_graphs()

    # =============================================================================
    # %% Load Image
    # =============================================================================

    originalDir = os.getcwd()

    samplefileName = easyqt.get_file_names("Choose one of the scan files")[0]

    data_dir = samplefileName.rsplit('/', 1)[0]
    os.chdir(data_dir)

    try:
        os.mkdir(data_dir + '/output/')
    except:
        pass

    fname2save = data_dir + '/output/' + samplefileName.rsplit(
        '_', 1)[0].rsplit('/', 1)[1]

    wpu.print_blue('MESSAGE: Loading files ' +
                   samplefileName.rsplit('_', 1)[0] + '*.tif')

    listOfDataFiles = glob.glob(samplefileName.rsplit('_', 2)[0] + '*.tif')
    listOfDataFiles.sort()
    nfiles = len(listOfDataFiles)

    zvec_from = easyqt.get_choice(
        message='z distances is calculated or from table?',
        title='Title',
        choices=['Calculated', 'Tabled'])

    # %%

    if zvec_from == 'Calculated':

        startDist = easyqt.get_float('Starting distance scan [mm]',
                                     title='Title',
                                     default_value=20) * 1e-3

        step_z_scan = easyqt.get_float(
            'Step size scan [mm]', title='Title', default_value=5) * 1e-3

        image_per_point = easyqt.get_int('Number of images by step',
                                         title='Title',
                                         default_value=1)

        zvec = np.linspace(
            startDist,
            startDist + step_z_scan * (nfiles / image_per_point - 1),
            int(nfiles / image_per_point))
        zvec = zvec.repeat(image_per_point)

        strideFile = easyqt.get_int('Stride (Use only every XX files)',
                                    title='Title',
                                    default_value=1)
        listOfDataFiles = listOfDataFiles[0::strideFile]
        zvec = zvec[0::strideFile]
        print(zvec)
    elif zvec_from == 'Tabled':

        zvec = np.loadtxt(
            easyqt.get_file_names("Table with the z distance values in mm")
            [0]) * 1e-3
        step_z_scan = np.mean(np.diff(zvec))

    if step_z_scan > 0:
        pass
    else:
        listOfDataFiles = listOfDataFiles[::-1]
        zvec = zvec[::-1]

    img = dxchange.read_tiff(listOfDataFiles[0])

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

    pixelSize = easyqt.get_float("Enter Pixel Size [um]",
                                 title='Experimental Values',
                                 default_value=.6500,
                                 decimals=5) * 1e-6

    gratingPeriod = easyqt.get_float("Enter CB Grating Period [um]",
                                     title='Experimental Values',
                                     default_value=4.8) * 1e-6

    pattern = easyqt.get_choice(message='Select CB Grating Pattern',
                                title='Title',
                                choices=['Diagonal', 'Edge'])
    #                            choices=['Edge', 'Diagonal'])

    sourceDistanceV = easyqt.get_float(
        "Enter Distance to Source\n in the VERTICAL [m]",
        title='Experimental Values',
        default_value=-0.73)

    sourceDistanceH = easyqt.get_float(
        "Enter Distance to Source\n in the Horizontal [m]",
        title='Experimental Values',
        default_value=34.0)

    unFilterSize = easyqt.get_int("Enter Size for Uniform Filter [Pixels]\n" +
                                  "    (Enter 1 to NOT use the filter)",
                                  title='Experimental Values',
                                  default_value=1)

    searchRegion = easyqt.get_int(
        "Enter Size of Region for Searching\n the Peak [in Pixels]",
        title='Experimental Values',
        default_value=20)

    os.chdir(originalDir)

    # =============================================================================
    # %% Crop
    # =============================================================================

    idx4crop = [0, -1, 0, -1]

    [colorlimit, cmap] = wpu.plot_slide_colorbar(
        img,
        title='SELECT COLOR SCALE,\n' + 'Raw Image, No Crop',
        xlabel=r'x [$\mu m$ ]',
        ylabel=r'y [$\mu m$ ]',
        extent=wpu.extent_func(img, pixelSize) * 1e6)

    idx4crop = wpu.graphical_roi_idx(img,
                                     verbose=True,
                                     kargs4graph={
                                         'cmap': cmap,
                                         'vmin': colorlimit[0],
                                         'vmax': colorlimit[1]
                                     })

    wpu.print_blue("MESSAGE: idx for cropping")
    wpu.print_blue(idx4crop)

    # =============================================================================
    # %% Dark indexes
    # =============================================================================

    darkRegionSelctionFlag = easyqt.get_yes_or_no(
        'Do you want to select ' + 'region for dark calculation?\n' +
        'Press ESC to use [0, 20, 0, 20]')

    if darkRegionSelctionFlag:

        idx4cropDark = wpu.graphical_roi_idx(img,
                                             verbose=True,
                                             kargs4graph={
                                                 'cmap': cmap,
                                                 'vmin': colorlimit[0],
                                                 'vmax': colorlimit[1]
                                             })
    else:
        idx4cropDark = [0, 20, 0, 20]

    # dark_im = dxchange.read_tiff(listOfDataFiles[0])*0.0 + avgDark

    img = wpu.crop_matrix_at_indexes(img, idx4crop)

    # ==============================================================================
    # %% Harmonic Periods
    # ==============================================================================

    if pattern == 'Diagonal':
        period_harm_Vert = np.int(
            np.sqrt(2) * pixelSize / gratingPeriod * img.shape[0])
        period_harm_Horz = np.int(
            np.sqrt(2) * pixelSize / gratingPeriod * img.shape[1])
    elif pattern == 'Edge':
        period_harm_Vert = np.int(2 * pixelSize / gratingPeriod * img.shape[0])
        period_harm_Horz = np.int(2 * pixelSize / gratingPeriod * img.shape[1])

    # Obtain harmonic periods from images

    (period_harm_Vert,
     _) = wgi.exp_harm_period(img, [period_harm_Vert, period_harm_Horz],
                              harmonic_ij=['1', '0'],
                              searchRegion=40,
                              isFFT=False,
                              verbose=True)

    (_, period_harm_Horz) = wgi.exp_harm_period(
        img, [period_harm_Vert, period_harm_Horz],
        harmonic_ij=['0', '1'],
        searchRegion=40,
        isFFT=False,
        verbose=True)

    wpu.log_this('Input files: ' + samplefileName.rsplit('_', 1)[0] + '*.tif',
                 preffname=fname2save)
    wpu.log_this('\nNumber of files : ' + str(nfiles))
    wpu.log_this('Stride : ' + str(strideFile))
    wpu.log_this('Z distances is ' + zvec_from)

    if zvec_from == 'Calculated':
        wpu.log_this('Step zscan [mm] : {:.4g}'.format(step_z_scan * 1e3))
        wpu.log_this('Start point zscan [mm] : {:.4g}'.format(startDist * 1e3))

    wpu.log_this('Pixel Size [um] : {:.4g}'.format(pixelSize * 1e6))
    wpu.log_this('Grating Period [um] : {:.4g}'.format(gratingPeriod * 1e6))
    wpu.log_this('Grating Pattern : ' + pattern)
    wpu.log_this('Crop idxs : ' + str(idx4crop))
    wpu.log_this('Dark idxs : ' + str(idx4cropDark))

    wpu.log_this('Vertical Source Distance: ' + str(sourceDistanceV))
    wpu.log_this('Horizontal Source Distance: ' + str(sourceDistanceH))

    wpu.log_this('Uniform Filter Size : {:d}'.format(unFilterSize))

    wpu.log_this('Search Region : {:d}'.format(searchRegion))

    # =============================================================================
    # %% Calculate everything
    # =============================================================================

    # =============================================================================
    # %% multiprocessing
    # =============================================================================

    ncpus = cpu_count()

    wpu.print_blue("MESSAGE: %d cpu's available" % ncpus)

    tzero = time.time()

    p = Pool(ncpus - 5)

    indexes = range(len(listOfDataFiles))
    parameters = []

    for i in indexes:
        parameters.append([
            i, listOfDataFiles, zvec, idx4cropDark, idx4crop, period_harm_Vert,
            sourceDistanceV, period_harm_Horz, sourceDistanceH, searchRegion,
            unFilterSize
        ])

    res = p.map(_func, parameters)
    p.close()

    wpu.print_blue('MESSAGE: Time spent: {0:.3f} s'.format(time.time() -
                                                           tzero))
    '''
    res = []
    for i in range(len(listOfDataFiles)):
        res.append(_func(i))
    print(res)
    '''
    # =============================================================================
    # %% Sorting the data
    # =============================================================================

    contrastV = np.asarray([x[0] for x in res])
    contrastH = np.asarray([x[1] for x in res])

    p0 = np.asarray([x[2] for x in res])
    pv = np.asarray([x[3] for x in res])
    ph = np.asarray([x[4] for x in res])

    pattern_period_Vert_z = pixelSize / (pv[:, 0] - p0[:, 0]) * img.shape[0]
    pattern_period_Horz_z = pixelSize / (ph[:, 1] - p0[:, 1]) * img.shape[1]

    # =============================================================================
    # %% Save csv file
    # =============================================================================

    outputfname = wpu.get_unique_filename(fname2save, 'csv')

    wpu.save_csv_file(np.c_[zvec.T, contrastV.T, contrastH.T,
                            pattern_period_Vert_z.T, pattern_period_Horz_z.T],
                      outputfname,
                      headerList=[
                          'z [m]', 'Vert Contrast', 'Horz Contrast',
                          'Vert Period [m]', 'Horz Period [m]'
                      ])

    wpu.log_this('\nOutput file: ' + outputfname)

    # =============================================================================
    # %% Plot
    # =============================================================================

    # contrast vs z
    fig = plt.figure(figsize=(10, 7))
    plt.plot(zvec * 1e3, contrastV * 100, '-ko', label='Vert')
    plt.plot(zvec * 1e3, contrastH * 100, '-ro', label='Hor')
    plt.xlabel(r'Distance $z$  [mm]', fontsize=14)

    plt.ylabel(r'Visibility $\times$ 100 [%]', fontsize=14)
    plt.title('Visibility vs detector distance', fontsize=14, weight='bold')

    plt.legend(fontsize=14, loc=0)

    wpu.save_figs_with_idx(fname2save)
    plt.show(block=False)

    # =============================================================================
    # %% Plot Harmonic position and calculate source distance
    # =============================================================================
    #    from wavepytools.diag.coherence.fit_singleGratingCoherence_z_scan import fit_period_vs_z
    #xshi 20190719
    from fit_singleGratingCoherence_z_scan import fit_period_vs_z
    (sourceDistance_from_fit_V,
     patternPeriodFromData_V) = fit_period_vs_z(zvec,
                                                pattern_period_Vert_z,
                                                contrastV,
                                                direction='Vertical',
                                                threshold=.002,
                                                fname4graphs=fname2save)

    (sourceDistance_from_fit_H,
     patternPeriodFromData_H) = fit_period_vs_z(zvec,
                                                pattern_period_Horz_z,
                                                contrastH,
                                                direction='Horizontal',
                                                threshold=0.0005,
                                                fname4graphs=fname2save)
예제 #19
0
def single_grating_harmonic_images(img, harmonicPeriod,
                                   searchRegion=10,
                                   plotFlag=False, verbose=False):
    """
    Auxiliary function to process the data of single 2D grating Talbot imaging.
    It obtain the (real space) harmonic images  00, 01 and 10.

    Parameters
    ----------
    img : 	ndarray – Data (data_exchange format)
        Experimental image, whith proper blank image, crop and rotation already
        applied.

    harmonicPeriod : list of integers in the format [periodVert, periodHor]
        ``periodVert`` and ``periodVert`` are the period of the harmonics in
        the reciprocal space in pixels. For the checked board grating,
        periodVert = sqrt(2) * pixel Size / grating Period * number of
        rows in the image. For 1D grating, set one of the values to negative or
        zero (it will set the period to number of rows or colunms).

    searchRegion: int
        search for the peak will be in a region of harmonicPeriod/searchRegion
        around the theoretical peak position. See also
        `:py:func:`wavepy.grating_interferometry.plot_harmonic_grid`

    plotFlag: boolean
        Flag to plot the image in the reciprocal space and to show the position
        of the found peaked and the limits of the harmonic image

    verbose: Boolean
        verbose flag.

    Returns
    -------
    three 2D ndarray data
        Images obtained from the harmonics 00, 01 and 10.

    """

    imgFFT = np.fft.fftshift(fft2(img, norm='ortho'))

    if plotFlag:
        plot_harmonic_grid(imgFFT, harmonicPeriod=harmonicPeriod, isFFT=True)
        plt.show(block=False)

    imgFFT00 = extract_harmonic(imgFFT,
                                harmonicPeriod=harmonicPeriod,
                                harmonic_ij='00',
                                searchRegion=searchRegion,
                                isFFT=True,
                                plotFlag=plotFlag,
                                verbose=verbose)

    imgFFT01 = extract_harmonic(imgFFT,
                                harmonicPeriod=harmonicPeriod,
                                harmonic_ij=['0', '1'],
                                searchRegion=searchRegion,
                                isFFT=True,
                                plotFlag=plotFlag,
                                verbose=verbose)

    imgFFT10 = extract_harmonic(imgFFT,
                                harmonicPeriod=harmonicPeriod,
                                harmonic_ij=['1', '0'],
                                searchRegion=searchRegion,
                                isFFT=True,
                                plotFlag=plotFlag,
                                verbose=verbose)

    #  Plot Fourier image (intensity)
    if plotFlag:

        # Intensity is Fourier Space
        intFFT00 = np.log10(np.abs(imgFFT00))
        intFFT01 = np.log10(np.abs(imgFFT01))
        intFFT10 = np.log10(np.abs(imgFFT10))

        fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(14, 5))

        for dat, ax, textTitle in zip([intFFT00, intFFT01, intFFT10],
                                      axes.flat,
                                      ['FFT 00', 'FFT 01', 'FFT 10']):

            # The vmin and vmax arguments specify the color limits
            im = ax.imshow(dat, cmap='inferno', vmin=np.min(intFFT00),
                           vmax=np.max(intFFT00),
                           extent=wpu.extent_func(dat))

            ax.set_title(textTitle)
            if textTitle == 'FFT 00':
                ax.set_ylabel('Pixels')

            ax.set_xlabel('Pixels')

        # Make an axis for the colorbar on the right side
        cax = fig.add_axes([0.92, 0.1, 0.03, 0.8])
        fig.colorbar(im, cax=cax)
        plt.suptitle('FFT subsets - Intensity', fontsize=18, weight='bold')
        plt.show(block=False)

    img00 = ifft2(np.fft.ifftshift(imgFFT00), norm='ortho')

    # non existing harmonics will return NAN, so here we check NAN
    if np.all(np.isfinite(imgFFT01)):
        img01 = ifft2(np.fft.ifftshift(imgFFT01), norm='ortho')
    else:
        img01 = imgFFT01

    if np.all(np.isfinite(imgFFT10)):
        img10 = ifft2(np.fft.ifftshift(imgFFT10), norm='ortho')
    else:
        img10 = imgFFT10

    return (img00, img01, img10)
예제 #20
0
    default_value=20)

os.chdir(originalDir)

# =============================================================================
# %% Crop
# =============================================================================

idx4crop = [0, -1, 0, -1]

[colorlimit, cmap] = wpu.plot_slide_colorbar(
    img,
    title='SELECT COLOR SCALE,\n' + 'Raw Image, No Crop',
    xlabel=r'x [$\mu m$ ]',
    ylabel=r'y [$\mu m$ ]',
    extent=wpu.extent_func(img, pixelSize) * 1e6)

idx4crop = wpu.graphical_roi_idx(img,
                                 verbose=True,
                                 kargs4graph={
                                     'cmap': cmap,
                                     'vmin': colorlimit[0],
                                     'vmax': colorlimit[1]
                                 })

wpu.print_blue("MESSAGE: idx for cropping")
wpu.print_blue(idx4crop)

img = wpu.crop_matrix_at_indexes(img, idx4crop)

# =============================================================================
예제 #21
0
def plot_integration(integrated, pixelsize,
                     titleStr='Title', ctitle=' ', saveFigFlag=False,
                     saveFileSuf='graph'):
    '''
    TODO: Write Docstring
    '''

    xxGrid, yyGrid = wpu.grid_coord(integrated, pixelsize)

    factor_x, unit_x = wpu.choose_unit(xxGrid)
    factor_y, unit_y = wpu.choose_unit(yyGrid)

    wpu.plot_profile(xxGrid*factor_x, yyGrid*factor_y,   integrated[::-1, :],
                     xlabel=r'$x [' + unit_x + ' m]$',
                     ylabel=r'$y [' + unit_y + ' m]$',
                     title=titleStr,
                     xunit='\mu m', yunit='\mu m',
                     arg4main={'cmap': 'viridis', 'lw': 3})

    if saveFigFlag:
        plt.ioff()

        plt.figure(figsize=(10, 8))

        plt.imshow(integrated[::-1, :], cmap='viridis',
                   extent=wpu.extent_func(integrated, pixelsize)*factor_x)

        plt.xlabel(r'$x [' + unit_x + ' m]$', fontsize=24)
        plt.ylabel(r'$y [' + unit_x + ' m]$', fontsize=24)

        plt.title(titleStr, fontsize=18, weight='bold')
        cbar = plt.colorbar()
        cbar.ax.set_title(ctitle, y=1.01)
        wpu.save_figs_with_idx(saveFileSuf)
        #        plt.show(block=False)
        plt.close(plt.gcf())
        plt.ion()

    # Plot Integration 2

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

    rstride = integrated.shape[0] // 101 + 1
    cstride = integrated.shape[1] // 101 + 1

    surf = ax.plot_surface(xxGrid*factor_x, yyGrid*factor_y,
                           integrated[::-1, :],
                           rstride=rstride,
                           cstride=cstride,
                           cmap='viridis', linewidth=0.1)

    ax_lim = np.max([np.abs(xxGrid*factor_x), np.abs(yyGrid*factor_y)])
    ax.set_xlim3d(-ax_lim, ax_lim)
    ax.set_ylim3d(-ax_lim, ax_lim)

    plt.xlabel(r'$x [' + unit_x + ' m]$', fontsize=24)
    plt.ylabel(r'$y [' + unit_y + ' m]$', fontsize=24)

    plt.title(titleStr, fontsize=24, weight='bold')
    cbar = plt.colorbar(surf, shrink=.8, aspect=20)
    cbar.ax.set_title(ctitle, y=1.01)

    fig.tight_layout()

    plt.tight_layout()
    if saveFigFlag:
        wpu.save_figs_with_idx(saveFileSuf)

    ax.text2D(0.05, 0.9, 'strides = {}, {}'.format(rstride, cstride),
              transform=ax.transAxes)

    plt.show(block=False)

    return ax