Example #1
0
def unwrap_plots():
    
    x, y = np.ogrid[:32, :32]
    phi = 2*np.pi*(x*0.2 + y*0.1)

    #phi = 1*np.arctan2(x-14.3, y-6.3) - 2*np.arctan2(x-18.3, y-22.1)

    phi[8,8] = np.NaN
    
    phi_wrapped = np.angle(np.exp(1j*phi))
    phi_unwrapped = unwrap(phi_wrapped, 
                           #wrap_around_axis_0 = True,
                           #wrap_around_axis_1 = True,
                           )

    mask = np.zeros_like(phi, dtype = np.uint8)
    #mask[10:22, 4:10] = 1
    phi_wrapped_masked = np.ma.array(phi_wrapped, dtype = np.float32, mask = mask)
    phi_unwrapped_masked = unwrap(phi_wrapped_masked)
    
    import matplotlib.pyplot as plt
    plt.figure(1)
    plt.clf()
    plt.gray()
    plt.subplot(221)
    plt.imshow(phi, interpolation = 'nearest')
    plt.subplot(222)
    plt.imshow(phi_wrapped, interpolation = 'nearest')
    plt.subplot(223)
    plt.imshow(phi_unwrapped, interpolation = 'nearest')
    plt.subplot(224)
    plt.imshow(phi_unwrapped_masked, interpolation = 'nearest')

    plt.draw()
    plt.show()
Example #2
0
def calculate_phase_diff_map_1d(dY, dY0, th, ns, mask_for_unwrapping=None):
    """
    TODO: Docstring for calculate_phase_diff_map_1d
    # Basic FTP treatment.
    # This function takes a deformed and a reference image and calculates the phase difference map between the two.
    #
    # INPUTS:
    # dY	= deformed image
    # dY0	= reference image
    # ns	= size of gaussian filter
    #
    # OUTPUT:
    # dphase 	= phase difference map between images
    """

    ny, nx = np.shape(dY)
    phase0 = np.zeros([nx, ny])
    phase = np.zeros([nx, ny])

    for lin in range(0, nx):
        fY0 = np.fft.fft(dY0[lin, :])
        fY = np.fft.fft(dY[lin, :])

        dfy = 1. / ny
        fy = np.arange(dfy, 1, dfy)

        imax = np.argmax(np.abs(fY0[9:nx // 2]))
        ifmax = imax + 9

        HW = np.round(ifmax * th)
        HW *= 0.5  # TODO
        W = 2 * HW
        win = signal.tukey(int(W), ns)

        gaussfilt1D = np.zeros(nx)
        gaussfilt1D[int(ifmax - HW - 1):int(ifmax - HW + W - 1)] = win

        Nfy0 = fY0 * gaussfilt1D
        Nfy = fY * gaussfilt1D

        Ny0 = np.fft.ifft(Nfy0)
        Ny = np.fft.ifft(Nfy)

        phase0[lin, :] = np.angle(Ny0)
        phase[lin, :] = np.angle(Ny)

    if mask_for_unwrapping is None:
        mphase0 = unwrap(phase0)
        mphase = unwrap(phase)
    else:
        mphase0 = ma.masked_array(phase0, mask=mask_for_unwrapping)
        mphase = ma.masked_array(phase, mask=mask_for_unwrapping)
        mphase0 = unwrap(mphase0)
        mphase = unwrap(mphase)

    dphase = (mphase - mphase0)
    return dphase
Example #3
0
def rescale_and_unwrap_3D(img,roi_mask):
    #First rescale:
    img=(np.float32(img)-2048)*(np.pi/2048)       
    #Then unwrap:    
    import unwrap
    img_unwrapped=unwrap.unwrap(np.ma.masked_array(img,roi_mask))
    return img_unwrapped
Example #4
0
def rescale_and_unwrap_3D(img, roi_mask):
    # First rescale:
    img = (np.float32(img) - 2048) * (np.pi / 2048)
    # Then unwrap:
    import unwrap
    img_unwrapped = unwrap.unwrap(np.ma.masked_array(img, roi_mask))
    return img_unwrapped
Example #5
0
def pypi_unwrap(phase):
    unwrapped_phase = unwrap.unwrap(phase,
                                    wrap_around_axis_0=False,
                                    wrap_around_axis_1=False,
                                    wrap_around_axis_2=False)

    return unwrapped_phase
def get_st_diagram(med_folder_name):
    hdf5_path = f'../../../Mediciones/{med_folder_name}/HDF5/ST.hdf5'
    f = h5py.File(hdf5_path, 'r')

    st_diagram = np.array(f['spatiotemporal_diagram'])

    gap = st_diagram[:, 100] - np.unwrap(st_diagram[:, 100])

    gap = np.expand_dims(gap, 1)
    st_diagram = st_diagram - gap

    st_diagram = unwrap(st_diagram)

    st_diagram -= np.expand_dims(st_diagram.mean(1), 1)

    st_diagram[(st_diagram > 5) + (st_diagram < -5)] = np.nan
    st_diagram = fill_nans(st_diagram)

    st_diagram *= -1

    #  st_diagram = np.remainder(st_diagram, 2*np.pi)
    #  st_diagram[st_diagram < 1.2] = np.nan
    #  st_diagram = fill_nans(st_diagram)
    #  st_diagram = np.pi - st_diagram

    #  st_diagram = (st_diagram.T - st_diagram.mean(1)).T
    #  mask = (st_diagram > 5) + (st_diagram < -5)
    #  st_diagram[mask] = np.nan
    #  st_diagram = fill_nans(st_diagram)
    #  st_diagram *= -1

    return st_diagram
def joint_likelihood_integrate(combined_params, Y, resp, example_params_struct, prior):
    # First, unpack parameters.  
    cur_params = rewrap( example_params_struct, combined_params )

    (nll_mix, dnll_mix_X) = mixture_likelihood_integrate(cur_params['X'], resp, prior)
    ##checkgrad('mixture_likelihood_integrate', cur_params.X, 1e-6, resp);
    
    
    (nll_lvm, dnll_lvm_X, dnll_log_hypers) = gplvm_likelihood(cur_params.X, Y, cur_params['log_hypers'])
    ##checkgrad('gplvm_likelihood', combined_params, 1e-6);

    ##[ nll_back, dnll_back_X, dnll_log_hypers_back ] = ...
    ##    back_constraint_likelihood( cur_params.X, Y, cur_params.log_hypers );
    nll_back = 0
    dnll_back_X = 0
    ##checkgrad('back_constraint_likelihood', cur_params.X, 1e-6, Y,
    ##cur_params.log_hypers);
    
    nll =  nll_lvm + nll_mix + nll_back
    
    ## Put gradients back into a vector.
    all_grads_struct['X'] = np.matrix(dnll_lvm_X) + np.matrix(dnll_mix_X) + dnll_back_X
    all_grads_struct['log_hypers'] = dnll_log_hypers
    dnll = unwrap(all_grads_struct)
    
    return (nll, dnll)
Example #8
0
    def test_unwrap2D(self):
        x, y = np.ogrid[:8, :16]
        phi = 2*np.pi*(x*0.2 + y*0.1)
        phi_wrapped = np.angle(np.exp(1j*phi))
        phi_unwrapped = unwrap(phi_wrapped)

        s = np.round(phi_unwrapped[0,0]/(2*np.pi))
        assert_array_almost_equal(phi, phi_unwrapped - s*2*np.pi)
Example #9
0
    def test_unwrap2D(self):
        x, y = np.ogrid[:8, :16]
        phi = 2 * np.pi * (x * 0.2 + y * 0.1)
        phi_wrapped = np.angle(np.exp(1j * phi))
        phi_unwrapped = unwrap(phi_wrapped)

        s = np.round(phi_unwrapped[0, 0] / (2 * np.pi))
        assert_array_almost_equal(phi, phi_unwrapped - s * 2 * np.pi)
Example #10
0
 def test_unwrap3D_y_wraparound(self):
     """
     Regression test for an incorrect addressing when wrapping around Y-axis is enabled.
     Produced a segfault.
     """
     x, y, z = np.ogrid[:11, :128, :128]
     phi = 2 * np.pi * (x * 0.2 + y * 0.1 + z * 0.05)
     phi_wrapped = np.angle(np.exp(1j * phi))
     phi_unwrapped = unwrap(phi_wrapped, wrap_around_axis_1=True)
Example #11
0
 def test_unwrap3D_y_wraparound(self):
     """
     Regression test for an incorrect addressing when wrapping around Y-axis is enabled.
     Produced a segfault.
     """
     x, y, z = np.ogrid[:11, :128, :128]
     phi = 2*np.pi*(x*0.2 + y*0.1 + z*0.05)
     phi_wrapped = np.angle(np.exp(1j*phi))
     phi_unwrapped = unwrap(phi_wrapped, wrap_around_axis_1=True)
Example #12
0
def calc_B0_map(folder,roi_mask):
    from human_SWI_data import phase_rescale
    import unwrap
    images,TE=read_dicoms(folder,'EchoTime')   
    phase_images = [phase_rescale(img) for img in images]
    roi_mask_inv=np.zeros_like(roi_mask)
    roi_mask_inv[roi_mask==1]=0
    roi_mask_inv[roi_mask==0]=1
    phase_images_unwrapped=[unwrap.unwrap(np.ma.masked_array(img,roi_mask_inv)) for img in phase_images]
    return phase_images_unwrapped
Example #13
0
    def test_unwrap3D_masked(self):
        x, y, z = np.ogrid[:8, :12, :4]
        phi = 2*np.pi*(x*0.2 + y*0.1 + z*0.05)
        phi_wrapped = np.angle(np.exp(1j*phi))
        mask = np.zeros_like(phi, dtype = np.uint8)
        mask[4:6, 4:6, 1:3] = 1
        phi_wrapped_masked = np.ma.array(phi_wrapped, dtype = np.float32, mask = mask)
        phi_unwrapped_masked = unwrap(phi_wrapped_masked)

        s = np.round(phi_unwrapped_masked[0,0,0]/(2*np.pi))
        assert_array_almost_equal(phi + 2*np.pi*s, phi_unwrapped_masked)
Example #14
0
    def test_unwrap3D_masked(self):
        x, y, z = np.ogrid[:8, :12, :4]
        phi = 2 * np.pi * (x * 0.2 + y * 0.1 + z * 0.05)
        phi_wrapped = np.angle(np.exp(1j * phi))
        mask = np.zeros_like(phi, dtype=np.uint8)
        mask[4:6, 4:6, 1:3] = 1
        phi_wrapped_masked = np.ma.array(
            phi_wrapped, dtype=np.float32, mask=mask)
        phi_unwrapped_masked = unwrap(phi_wrapped_masked)

        s = np.round(phi_unwrapped_masked[0, 0, 0] / (2 * np.pi))
        assert_array_almost_equal(phi + 2 * np.pi * s, phi_unwrapped_masked)
Example #15
0
def plot_one_line(med_folder_name, n_column=10):
    st_diagram = get_st_diagram(med_folder_name)

    fig, ax = plt.subplots(figsize=(12, 8))
    gap = st_diagram[:, n_column] - np.unwrap(st_diagram[:, n_column])

    st_diagram = (st_diagram.T - gap).T

    ax.imshow(unwrap(st_diagram))
    # plt.colorbar()

    plt.show()
Example #16
0
def calc_B0_map(folder, roi_mask):
    from human_SWI_data import phase_rescale
    import unwrap
    images, TE = read_dicoms(folder, 'EchoTime')
    phase_images = [phase_rescale(img) for img in images]
    roi_mask_inv = np.zeros_like(roi_mask)
    roi_mask_inv[roi_mask == 1] = 0
    roi_mask_inv[roi_mask == 0] = 1
    phase_images_unwrapped = [
        unwrap.unwrap(np.ma.masked_array(img, roi_mask_inv))
        for img in phase_images
    ]
    return phase_images_unwrapped
Example #17
0
def unwrap_plots():

    x, y = np.ogrid[:32, :32]
    phi = 1 * np.arctan2(x - 14.3, y - 6.3) - 2 * np.arctan2(
        x - 18.3, y - 22.1)

    #phi[8,8] = np.NaN

    phi_wrapped = np.angle(np.exp(1j * phi))
    phi_unwrapped = unwrap(
        phi_wrapped,
        #wrap_around_axis_0 = True,
        #wrap_around_axis_1 = True,
    )

    mask = np.zeros_like(phi, dtype=np.uint8)
    mask[10:22, 4:10] = 1
    phi_wrapped_masked = np.ma.array(phi_wrapped, dtype=np.float32, mask=mask)
    phi_unwrapped_masked = unwrap(phi_wrapped_masked)

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    fig = plt.figure()
    plt.gray()
    s = fig.add_subplot(221)
    s.imshow(phi, interpolation='nearest')
    s.set_title('original phase')
    s = fig.add_subplot(222)
    s.imshow(phi_wrapped, interpolation='nearest')
    s.set_title('wrapped phase')
    s = fig.add_subplot(223)
    s.imshow(phi_unwrapped, interpolation='nearest')
    s.set_title('unwrapped phase')
    s = fig.add_subplot(224)
    s.imshow(phi_unwrapped_masked, interpolation='nearest')
    s.set_title('unwrapped phase with mask')
    fig.savefig('test.png')
Example #18
0
def unwrap_plots():

    x, y = np.ogrid[:32, :32]
    phi = 1*np.arctan2(x-14.3, y-6.3) - 2*np.arctan2(x-18.3, y-22.1)

    #phi[8,8] = np.NaN

    phi_wrapped = np.angle(np.exp(1j*phi))
    phi_unwrapped = unwrap(phi_wrapped,
                           #wrap_around_axis_0 = True,
                           #wrap_around_axis_1 = True,
                           )

    mask = np.zeros_like(phi, dtype = np.uint8)
    mask[10:22, 4:10] = 1
    phi_wrapped_masked = np.ma.array(phi_wrapped, dtype = np.float32, mask = mask)
    phi_unwrapped_masked = unwrap(phi_wrapped_masked)

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    fig = plt.figure()
    plt.gray()
    s = fig.add_subplot(221)
    s.imshow(phi, interpolation = 'nearest')
    s.set_title('original phase')
    s = fig.add_subplot(222)
    s.imshow(phi_wrapped, interpolation = 'nearest')
    s.set_title('wrapped phase')
    s = fig.add_subplot(223)
    s.imshow(phi_unwrapped, interpolation = 'nearest')
    s.set_title('unwrapped phase')
    s = fig.add_subplot(224)
    s.imshow(phi_unwrapped_masked, interpolation = 'nearest')
    s.set_title('unwrapped phase with mask')
    fig.savefig('test.png')
Example #19
0
def sinogram_as_radon(uSin, align=True):
    u""" Computes the phase from a complex wave field sinogram.

    This step is essential when using the ray approximation before
    computation of the refractive index with the inverse Radon
    transform.

    Parameters
    ----------
    uSin : 2d or 3d complex ndarray
        The background-corrected sinogram of the complex scattered wave
        :math:`u(\mathbf{r})/u_0(\mathbf{r})`. The first axis iterates
        through the angles :math:`\phi_0`.
    align : bool
        Tries to correct for a phase offset in the phase sinogram.

    Returns
    -------
    phase : 2d or 3d real ndarray
        The unwrapped phase array corresponding to ``uSin``.

    Notes
    -----
    The phase-unwrapping is performed with the `unwrap`_ package.

    .. _unwrap: https://pypi.python.org/pypi/unwrap
    """
    ndims = len(uSin.shape)

    if ndims == 2:
        # unwrapping is very important
        phiR = np.unwrap(np.angle(uSin), axis=-1)
    else:
        # Unwrap gets the dimension of the problem from the input
        # data. Since we have a sinogram, we need to pass it the
        # slices one by one.
        phiR = np.angle(uSin)
        for i in range(len(phiR)):
            phiR[i] = unwrap.unwrap(phiR[i])

    if align:
        align_unwrapped(phiR)

    return phiR
Example #20
0
    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples'  # X : (n_samples, *dim, n_channels)
        # Initialization
        batch_imgs = list()
        batch_labels = list()

        # Generate data
        for i in list_IDs_temp:
            # Store sample
            # print (self.pair[i][0])
            img = scipy.io.loadmat(self.pair[i][0])['wrap']
            img_normalized = normalize_angle(img)
            batch_imgs.append(img_normalized)

            label = unwrap(img,
                           wrap_around_axis_0=False,
                           wrap_around_axis_1=False,
                           wrap_around_axis_2=False)
            label_normalized = normalize_angle(label)
            batch_labels.append(label_normalized)

        return np.array(np.expand_dims(batch_imgs, axis=-1)), np.array(
            np.expand_dims(batch_labels, axis=-1))
Example #21
0
def calculate_phase_diff_map_1D(dY, dY0, th, ns, mask_for_unwrapping=None):
    """
    # % Basic FTP treatment.
    # % This function takes a deformed and a reference image and calculates the phase difference map between the two.
    # %
    # % INPUTS:
    # % dY	= deformed image
    # % dY0	= reference image
    # % ns	= size of gaussian filter
    # %
    # % OUTPUT:
    # % dphase 	= phase difference map between images
    """

    ny, nx = np.shape(dY)
    phase0 = np.zeros([nx,ny])
    phase  = np.zeros([nx,ny])

    for lin in range (0,nx):
        fY0=np.fft.fft(dY0[lin,:])
        fY=np.fft.fft(dY[lin,:])

        dfy=1./ny
        fy=np.arange(dfy,1,dfy)

        imax=np.argmax(np.abs(fY0[9:int(np.floor(nx/2))]))
        ifmax=imax+9

        HW=np.round(ifmax*th)
        W=2*HW
        win=signal.tukey(int(W),ns)


        # OJO QUE ACA LO MODIFIQUE
        #gaussfilt1D= np.zeros([1,nx])
        gaussfilt1D= np.zeros(nx)
        gaussfilt1D[int(ifmax-HW-1):int(ifmax-HW+W-1)]=win

        # Multiplication by the filter
        Nfy0 = fY0*gaussfilt1D
        Nfy = fY*gaussfilt1D

        # Inverse Fourier transform of both images
        Ny0=np.fft.ifft(Nfy0)
        Ny=np.fft.ifft(Nfy)
        
        phase0[lin,:] = np.angle(Ny0)
        phase[lin,:]  = np.angle(Ny)
    
    # 2D-unwrapping is available with masks (as an option), using 'unwrap' library
    # unwrap allows for the use of wrapped_arrays, according to the docs:
    # "[...] in this case masked entries are ignored during the phase unwrapping process. This is useful if the wrapped phase data has holes or contains invalid entries. [...]"

    if mask_for_unwrapping is None:
        mphase0 = unwrap(phase0)
        mphase = unwrap(phase)
    else:
        mphase0 = ma.masked_array(phase0, mask=mask_for_unwrapping)
        mphase  = ma.masked_array(phase,  mask=mask_for_unwrapping)
        mphase0 = unwrap(mphase0)
        mphase = unwrap(mphase)
    
    # Definition of the phase difference map
    dphase = (mphase-mphase0);
    # dphase = dphase - np.min(dphase) - np.pi/2 
    return dphase
    fB = odt.backpropagate_2d(u_sinB, angles, res, nmed, lD*res)
    nB = odt.odt_to_ri(fB, res, nmed)
    
    # Rytov
    u_sinR = odt.sinogram_as_rytov(sino/u0)
    fR = odt.backpropagate_2d(u_sinR, angles, res, nmed, lD*res)
    nR = odt.odt_to_ri(fR, res, nmed)
    
    # Rytov 50
    u_sinR50 = odt.sinogram_as_rytov((sino/u0)[::5,:])
    fR50 = odt.backpropagate_2d(u_sinR50, angles[::5], res, nmed, lD*res)
    nR50 = odt.odt_to_ri(fR50, res, nmed)
    
    
    # Plot sinogram phase and amplitude
    ph = unwrap.unwrap(np.angle(sino/u0))
    
    
    am = np.abs(sino/u0)

    # prepare plot
    
    vmin = np.min(np.array([phantom, nB.real, nR50.real, nR.real]))
    vmax = np.max(np.array([phantom, nB.real, nR50.real, nR.real]))
    
    fig, axes = plt.subplots(2,3, figsize=(12,7), dpi=300)
    axes = np.array(axes).flatten()
    
    phantommap = axes[0].imshow(phantom, vmin=vmin, vmax=vmax)
    axes[0].set_title("phantom \n(non-centered cylinder)")
    
A = cfg["A"]  # number of projections

x = np.arange(size) - size / 2.0
X, Y = np.meshgrid(x, x)
rad_px = radius * res
phantom = np.array(((Y - lC * res)**2 + X**2) < rad_px**2,
                   dtype=np.float) * (ncyl - nmed) + nmed

u_sinR = odt.sinogram_as_rytov(sino / u0)

# Rytov 200 projections
# remove 50 projections from total of 250 projections
remove200 = np.argsort(angles % .0002)[:50]
angles200 = np.delete(angles, remove200, axis=0)
u_sinR200 = np.delete(u_sinR, remove200, axis=0)
ph200 = unwrap.unwrap(np.angle(sino / u0))
ph200[remove200] = 0

fR200 = odt.backpropagate_2d(u_sinR200, angles200, res, nmed, lD * res)
nR200 = odt.odt_to_ri(fR200, res, nmed)
fR200nw = odt.backpropagate_2d(u_sinR200,
                               angles200,
                               res,
                               nmed,
                               lD * res,
                               weight_angles=False)
nR200nw = odt.odt_to_ri(fR200nw, res, nmed)

# Rytov 50 projections
remove50 = np.argsort(angles % .0002)[:200]
angles50 = np.delete(angles, remove50, axis=0)
def PhaseUnwrap(image, noZernikeModes, MIDDLE, DIAMETER, REGION=30):

    #convert image to array and float
    data = numpy.asarray(image)
    datafloat = numpy.zeros((data.shape), dtype=float)
    datafloat = data * 1.0

    #create the mask to cut out unwanted image areas
    mask = numpy.ones(data.shape)
    mask = cv2.circle(mask,
                      center=tuple(MIDDLE),
                      radius=int(round(DIAMETER / 2)),
                      color=0,
                      thickness=-1)
    mask = mask - 1
    mask = abs(mask)

    #mask image to remove extraneous data from edges
    datafloat = datafloat * mask

    #perform fourier transform and plot
    fftarray = numpy.fft.fft2(datafloat, norm='ortho')
    fftarray = numpy.fft.fftshift(fftarray)

    #remove center section to allow finding of 1st order point
    centre = [int(fftarray.shape[1] / 2), int(fftarray.shape[0] / 2)]
    order0 = numpy.log((fftarray[centre[1] - REGION:centre[1] + REGION,
                                 centre[0] - REGION:centre[0] + REGION]))
    fftarray[centre[1] - REGION:centre[1] + REGION,
             centre[0] - REGION:centre[0] + REGION] = 0.00001 + 0j

    #find first order point
    maxpoint = numpy.argmax(fftarray)
    maxpoint = [
        int(maxpoint % fftarray.shape[1]),
        int(maxpoint / fftarray.shape[1])
    ]
    order1 = ((fftarray[maxpoint[1] - REGION:maxpoint[1] + REGION,
                        maxpoint[0] - REGION:maxpoint[0] + REGION]))

    #pad the fftarray back to original size
    order1pad = numpy.zeros((data.shape), dtype=complex)
    index = numpy.zeros(4, dtype=int)
    index[0] = int((order1pad.shape[1] / 2) - (order1.shape[1] / 2))
    index[1] = int((order1pad.shape[1] / 2) + (order1.shape[1] / 2))
    index[2] = int((order1pad.shape[0] / 2) - (order1.shape[0] / 2))
    index[3] = int((order1pad.shape[0] / 2) + (order1.shape[0] / 2))
    order1pad[index[0]:index[1], index[2]:index[3]] = order1

    #shift the quadrants back to format for ifft use
    order1pad = numpy.fft.ifftshift(order1pad)

    #inverse fourier transform
    ifftorder1 = numpy.fft.ifft2(order1pad, norm='ortho')

    #mask ifftarray to remove extraneous data from edges
    ifftorder1 = ifftorder1 * mask

    #find phase data by taking 2d arctan of imaginary and real parts
    phaseorder1 = numpy.zeros(ifftorder1.shape)
    phaseorder1 = numpy.arctan2(ifftorder1.imag, ifftorder1.real)

    #mask out edge region to allow unwrap to only use correct region
    phasesave = phaseorder1
    phaseorder1mask = ma.masked_where(mask == 0, phaseorder1)

    #perform unwrap
    phaseunwrap = unwrap(phaseorder1mask)

    #crop to fill array to improve performance of zernike decomposition
    out = numpy.zeros((DIAMETER, DIAMETER), dtype=float)
    out = phaseunwrap[MIDDLE[1] - int(round(DIAMETER / 2)):MIDDLE[1] +
                      int(round(DIAMETER / 2)),
                      MIDDLE[0] - int(round(DIAMETER / 2)):MIDDLE[0] +
                      int(round(DIAMETER / 2))]
    out = out.filled(0)
    print("Calculating Zernike modes")
    coef, memLocation1 = opticspy.zernike.fitting(out, noZernikeModes)
    return coef, out
Example #25
0
 def unwrap(self, L_ion):  # L_ion is a pointer to an object
     unwrap(
         L_ion,
         [[self.xlo, self.xhi], [self.ylo, self.yhi], [self.zlo, self.zhi]])
Example #26
0
def calculate_phase_map(xt, ns=15, roll=True):
    """
    Obtains phase map from a spatiotemporal diagram.

    Parameters
    ----------
    xt : array
        Spatiotemporal diagram
    ns : int, optional
        Size of the gaussian filter (default is 15)
    roll: bool, optional
        If True, centers the signal before perfoeming the inverse Fourier Transform to obtain the phase

    Returns
    -------
    phase : array
        Phase map
    """

    phase = np.zeros_like(xt, dtype='float')
    ft    = np.fft.fft(xt, axis=1)

    ny, nx = np.shape(ft)
    th     = 0.9
    num    = 9

    max_array = np.zeros(xt.shape[0])
    for i in range(xt.shape[0]):
        ftlin = ft[i,:]
        imax=np.argmax(np.abs(ftlin[num:int(np.floor(nx/2))]))+num
        max_array[i] = imax
    ifmax = int(np.mean(max_array))

    HW=np.round(ifmax*th)
    W=2*HW
    win=signal.tukey(int(W),ns)

    gaussfilt1D= np.zeros(nx)
    gaussfilt1D[int(ifmax-HW-1):int(ifmax-HW+W-1)]=win

    for i in range(xt.shape[0]):
        ftlin = ft[i,:]
        # Multiplication by the filter
        Nfy = ftlin*gaussfilt1D
        if roll==True:
            c_centered = np.roll(Nfy, -ifmax)
        else:
            c_centered = Nfy
        # Inverse Fourier transform
        Cxt = np.fft.ifft(c_centered)
        # 1D unwrapping
        phi = np.unwrap(np.imag(np.log(Cxt)))
        phase[i,:] = phi

    # 2D unwrapping
    phase = unwrap(phase)

    # Mean substraction
    for i in range(xt.shape[0]):
        line_phase = np.unwrap(phase[i,:])
        phase[i,:] = line_phase-np.mean(line_phase)

    return phase
Example #27
0
def download_c(directory):
    directory += '-c'
    download(directory, relative_path('c.txt'))
    clean(directory, ['c', 'h'])
    unwrap(directory)
Example #28
0
File: eval.py Project: romty/PhU
    for i in range(start, end):
        pairs.append([('wrap/wraped_' + str(i + 1) + '.mat'),
                      ('unwrap/un_wraped_' + str(i + 1) + '.mat')])

    return pairs


from random import shuffle
test_pair = make_pair(3750, 4000)
from random import sample, choice
temp = choice(test_pair)
print(temp[0], "GAB", temp[1])
import matplotlib.pyplot as plt
img = scipy.io.loadmat(temp[0])['wrap']
mask_x = unwrap(img,
                wrap_around_axis_0=False,
                wrap_around_axis_1=False,
                wrap_around_axis_2=False)
plt.figure(figsize=(10, 10))
plt.subplot(121)
plt.imshow(dg.normalize_angle(img), cmap='jet')
plt.subplot(122)
plt.imshow(dg.normalize_angle(mask_x), cmap='jet')
plt.show()
class_map = 1
test_generator = dg.DataGenerator(test_pair,
                                  class_map,
                                  batch_size=20,
                                  dim=(256, 256, 1),
                                  shuffle=True)
test_steps = test_generator.__len__()
test_steps
Example #29
0
from example_helper import load_cell

# load initial cell
cell1 = load_cell("HL60_field.zip")

# refocus to two different positions
cell2 = nrefocus.refocus(cell1, 15, 1, 1)  # forward
cell3 = nrefocus.refocus(cell1, -15, 1, 1)  # backward

# amplitude range
vmina = np.min(np.abs(cell1))
vmaxa = np.max(np.abs(cell1))
ampkw = {"cmap": plt.get_cmap("gray"), "vmin": vmina, "vmax": vmaxa}

# phase range
cell1p = unwrap.unwrap(np.angle(cell1))
cell2p = unwrap.unwrap(np.angle(cell2))
cell3p = unwrap.unwrap(np.angle(cell3))
vminp = np.min(cell1p)
vmaxp = np.max(cell1p)
phakw = {"cmap": plt.get_cmap("coolwarm"), "vmin": vminp, "vmax": vmaxp}

# plots
fig, axes = plt.subplots(2, 3, figsize=(8, 4.5))
axes = axes.flatten()
for ax in axes:
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

# titles
axes[0].set_title("focused backward")
Example #30
0
def unwrap_3D(img, roi_mask):
    import unwrap
    img_unwrapped = unwrap.unwrap(np.ma.masked_array(img, roi_mask))
    return img_unwrapped
Example #31
0
def download_python(directory):
    directory += '-python'
    download(directory, relative_path('python.txt'))
    clean(directory, ['py'])
    unwrap(directory)
Example #32
0
def download_java(directory):
    directory += '-java'
    download(directory, relative_path('java.txt'))
    clean(directory, ['java'])
    unwrap(directory)
Example #33
0
def sinogram_as_rytov(uSin, u0=1, align=True):
    u""" Converts the complex wave field sinogram to Rytov data

    This method applies the Rytov approximation to the
    recorded complex wave sinogram. To achieve this, the following
    filter is applied:

    .. math::
        u_\mathrm{B}(\mathbf{r}) = u_\mathrm{0}(\mathbf{r})
            \ln\!\\left(  
            \\frac{u_\mathrm{R}(\mathbf{r})}{u_\mathrm{0}(\mathbf{r})}
             +1 \\right)

    This filter step effectively replaces the Born approximation
    :math:`u_\mathrm{B}(\mathbf{r})` with the Rytov approximation
    :math:`u_\mathrm{R}(\mathbf{r})`, assuming that the scattered
    field is equal to
    :math:`u(\mathbf{r})\\approx u_\mathrm{R}(\mathbf{r})+
    u_\mathrm{0}(\mathbf{r})`.
    

    Parameters
    ----------
    uSin : 2d or 3d complex ndarray
        The sinogram of the complex wave 
        :math:`u_\mathrm{R}(\mathbf{r}) + u_\mathrm{0}(\mathbf{r})`.
        The first axis iterates through the angles :math:`\phi_0`.
    u0 : ndarray of dimension as ``uSin`` or less, or int.
        The incident plane wave 
        :math:`u_\mathrm{0}(\mathbf{r})` at the detector.
        If ``u0`` is "1", it is assumed that the data is already
        background-corrected (
        ``uSin`` :math:`= \\frac{u_\mathrm{R}(\mathbf{r})}{
        u_\mathrm{0}(\mathbf{r})} + 1`
        ). Note that if the reconstruction distance :math:`l_\mathrm{D}`
        of the original experiment is non-zero and `u0` is set to 1,
        then the reconstruction will be wrong; the field is not focused
        to the center of the reconstruction volume.
    align : bool
        Tries to correct for a phase offset in the phase sinogram.

    Returns
    -------
    uB : 2d or 3d real ndarray
        The Rytov-filtered complex sinogram 
        :math:`u_\mathrm{B}(\mathbf{r})`.

    Notes
    -----
    The phase-unwrapping is performed with the `unwrap`_ package.

    .. _unwrap: https://pypi.python.org/pypi/unwrap    """
    ndims = len(uSin.shape)

    # imaginary part of the complex Rytov phase
    phiR = np.angle(uSin / u0)

    # real part of the complex Rytov phase
    lna = np.log(np.absolute(uSin / u0))

    if ndims == 2:
        # unwrapping is very important
        phiR[:] = np.unwrap(phiR, axis=-1)
    else:
        # Unwrap gets the dimension of the problem from the input
        # data. Since we have a sinogram, we need to pass it the
        # slices one by one.
        for i in range(len(phiR)):
            phiR[i] = unwrap.unwrap(phiR[i])

    if align:
        align_unwrapped(phiR)

    #rytovSin = u0*(np.log(a/a0) + 1j*phiR)
    # u0 is one - we already did background correction

    # complex rytov phase:
    rytovSin = 1j * phiR + lna
    return u0 * rytovSin
    A = cfg["A"] # number of projections

    #phantom = np.loadtxt(arc.open("mie_phantom.txt"))
    x = np.arange(size)-size/2.0
    X,Y = np.meshgrid(x,x)
    rad_px = radius*res
    phantom = np.array(((Y-lC*res)**2+X**2)<rad_px**2, dtype=np.float)*(ncyl-nmed)+nmed

    u_sinR = odt.sinogram_as_rytov(sino/u0)
    
    # Rytov 200 projections    
    # remove 50 projections from total of 250 projections
    remove200 = np.argsort(angles % .002)[:50]
    angles200 = np.delete(angles, remove200, axis=0)
    u_sinR200 = np.delete(u_sinR, remove200, axis=0)
    ph200 = unwrap.unwrap(np.angle(sino/u0))
    ph200[remove200] = 0
    
    fR200 = odt.backpropagate_2d(u_sinR200, angles200, res, nmed, lD*res)
    nR200 = odt.odt_to_ri(fR200, res, nmed)
    fR200nw = odt.backpropagate_2d(u_sinR200, angles200, res, nmed, lD*res, weight_angles=False)
    nR200nw = odt.odt_to_ri(fR200nw, res, nmed)
    
    
    # Rytov 50 projections
    remove50 = np.argsort(angles % .002)[:200]
    angles50 = np.delete(angles, remove50, axis=0)
    u_sinR50 = np.delete(u_sinR, remove50, axis=0)
    ph50 = unwrap.unwrap(np.angle(sino/u0))
    ph50[remove50] = 0
    
Example #35
0
+'Procesado FTP: '+str(round(tiempo_ftp/60,2))+' minutos'+'\n' \
+'Coordenadas polares: '+str(round(tiempo_coord_polares/60,2))+' minutos'+'\n' \
+'Tiempo total: '+str(round(round(tiempo_hdf5/60,2)+round(tiempo_ftp/60,2)+round(tiempo_coord_polares/60,2))) +' minutos'

# mensaje = str(filename) +'\n' \
# +'Procesado FTP: '+str(round(tiempo_ftp/60,2))+' minutos'+'\n' \
# +'Coordenadas polares: '+str(round(tiempo_coord_polares/60,2))+' minutos'+'\n' \
# +'Tiempo total: '+str(round(round(tiempo_ftp/60,2)+round(tiempo_coord_polares/60,2))) +' minutos'

print(mensaje)

f = h5py.File(destination_path+filename+'-annulus-PRO.hdf5','r')
p = f['height_fields/annulus_polar']
fps = 250
R1, R2 = (205/2)/10, (215/2)/10 #en cm
Rprom = (R1+R2)/2
xfinal = 2*np.pi*Rprom

plt.figure()
plt.imshow(unwrap(p), extent=[0,xfinal, 0, p.shape[1]/fps], aspect='auto',cmap='RdYlBu')
plt.clim((-1,1))
plt.colorbar()
plt.xlabel('longitud de arco (cm)')
plt.ylabel('tiempo (s)')
plt.title(filename)
plt.tight_layout()
plt.savefig(path_mediciones+'graficos/'+filename+'.png')

bot.send_photo(chat_id=my_id, photo=open(path_mediciones+'graficos/'+filename+'.png', 'rb'), caption=mensaje)
#bot.send_photo(chat_id=pablo_id, photo=open(path_mediciones+'graficos/'+filename+'.png', 'rb'), caption=mensaje)
Example #36
0
def unwrap2D(wraped_phase, type="boundary", noise=True):
    """
	2D unwarp function. There are several type to
	use in several different situation.

	Type:
	-----------------------------------------------
	Simple: The very simple algorithm to unwrap 2D warpped phase
			just scan the whole matrix to unwrap phase. Very noise
			sensitive

	boundary: 2D phase unwrap method for phase map with aperture,
			  for example, circle, rectangular, ring or slit. It
			  use a DFS(deep first search) algorithm to traverse
			  the phase map, then unwarp the phase.It is also very
			  noise sensitive
	etc: still have more, to be continue

	"""
    if type == "simple" and noise == False:
        l = len(wraped_phase)
        b = []
        b = np.array(b)
        for i in range(l):
            if i % 2 == 0:
                b = np.append(b, wraped_phase[i])
            else:
                b = np.append(b, wraped_phase[i][::-1])
        ph1 = unwrap1D(b)
        ph = np.zeros([l, l])
        for i in range(l):
            if i % 2 == 0:
                ph[i] = ph1[0:l]
                ph1 = ph1[l:]
            else:
                ph[i] = ph1[0:l][::-1]
                ph1 = ph1[l:]
        return ph

    elif type == "boundary" and noise == False:
        ph1 = wraped_phase[0]
        M = wraped_phase[1]
        s = wraped_phase[2]
        start_pixel = np.where(M == 1)
        m = start_pixel[0][0]
        n = start_pixel[1][0]
        print("start pixel", m, n)
        ph = DFS(M, ph1, m, n, s)
        return ph

    elif noise == True:
        ph1 = wraped_phase[0]
        M = wraped_phase[1]
        s = wraped_phase[2]
        ph = unwrap(ph1,wrap_around_axis_0=False,\
             wrap_around_axis_1=False,\
             wrap_around_axis_2=False)
        return ph

    else:
        print("No this type of unwrap algorithm")
        return 0
Example #37
0
def unwrap_3D(img, roi_mask):
    import unwrap
    img_unwrapped=unwrap.unwrap(np.ma.masked_array(img,roi_mask))
    return img_unwrapped
    res = cfg["res"] # px/wavelengths
    A = cfg["A"] # number of projections

    #phantom = np.loadtxt(arc.open("mie_phantom.txt"))
    x = np.arange(size)-size/2.0
    X,Y = np.meshgrid(x,x)
    rad_px = radius*res
    phantom = np.array(((Y-lC*res)**2+X**2)<rad_px**2, dtype=np.float)*(ncyl-nmed)+nmed

    u_sinR = odt.sinogram_as_rytov(sino/u0)
    
    # Rytov 100 projections evenly distributed    
    removeeven = np.argsort(angles % .002)[:150]
    angleseven = np.delete(angles, removeeven, axis=0)
    u_sinReven = np.delete(u_sinR, removeeven, axis=0)
    pheven = unwrap.unwrap(np.angle(sino/u0))
    pheven[removeeven] = 0
    
    fReven = odt.backpropagate_2d(u_sinReven, angleseven, res, nmed, lD*res)
    nReven = odt.odt_to_ri(fReven, res, nmed)
    fRevennw = odt.backpropagate_2d(u_sinReven, angleseven, res, nmed, lD*res, weight_angles=False)
    nRevennw = odt.odt_to_ri(fRevennw, res, nmed)
    
    
    # Rytov 100 projections more than 180
    removemiss = 249 - np.concatenate((np.arange(100), 100+np.arange(150)[::3]))
    anglesmiss = np.delete(angles, removemiss, axis=0)
    u_sinRmiss = np.delete(u_sinR, removemiss, axis=0)
    phmiss = unwrap.unwrap(np.angle(sino/u0))
    phmiss[removemiss] = 0