def _init_initial_support(self):
     if not self._initial_support_dirty:
         self._log("Initial support already initialised.","DEBUG")
         return
     for img in [self._sp_initial_support,self._sp_initial_support_sh]:
         if img is not None:
             spimage.sp_image_free(img)
     self._sp_initial_support = spimage.sp_image_alloc(self._Ny,self._Nx,1)
     if "radius" in self._initial_support_config or "area" in self._initial_support_config:
         X,Y = np.meshgrid(np.arange(self._Nx),np.arange(self._Ny))
         X = X-(self._Nx-1)/2.
         Y = Y-(self._Ny-1)/2.
         R = np.sqrt(X**2 + Y**2)
         self._phaser_dirty = True
         if "radius" in self._initial_support_config:
             r = self._initial_support_config["radius"]
         else:
             r = np.sqrt( self._initial_support_config["area"] * self._Nx * self._Ny / np.pi )
         self._sp_initial_support.image[:] = np.float32(np.fft.fftshift(R) < r)
     else:
         self._phaser_dirty = True
         S = self._initial_support_config["support_mask"]
         self.sep_initial_support.image[:] = np.float32(S)
     self._initial_support_dirty = False
     self._log("Initial support initialised.","DEBUG")
 def _clear_amplitudes(self):
     for img in [self._sp_amplitudes]:
         if img is not None:
             spimage.sp_image_free(img)
     self._amplitudes = None
     self._sp_amplitudes = None
     self._amplitudes_dirty = True
示例#3
0
def intensities_array_to_h5(img0,msk0,cx=None,cy=None,cropLength=None,save_to_file=None):
    import spimage,imgtools
    Nx = img0.shape[1]
    Ny = img0.shape[0]
    img = img0
    msk = msk0
    if cropLength != None:
        img = imgtools.crop(img0,cropLength,center=[cy,cx])
        msk = imgtools.crop(msk0,cropLength,center=[cy,cx])
        Nx = cropLength
        Ny = cropLength
    elif cx != None and cy != None:
        img = imgtools.recenter(img0,cx,cy)
        msk = imgtools.recenter(msk0,cx,cy)
    I = spimage.sp_image_alloc(Nx,Ny,1)
    I.image[:,:] = img[:,:]
    I.mask[:,:] = msk[:,:]
    I2 = spimage.sp_image_shift(I)
    I2.shifted = 0
    I2.phased = 0
    spimage.sp_image_free(I)
    if save_to_file != None:
        spimage.sp_image_write(I2,save_to_file,0)
    else:
        return I2
 def _clear_initial_support(self):
     for img in [self._sp_initial_support,self._sp_initial_support_sh]:
         if img is not None:
             spimage.sp_image_free(img)
     self._sp_initial_support = None
     self._sp_initial_support_sh = None
     self._initial_support_config = None
     self._initial_support_dirty = True
示例#5
0
def to_png(input_dir, output_dir, plot_setup):
    #color,shift_flag,support_flag = evaluate_arguments(arguments)
    files = read_files(input_dir)

    shift_function = get_shift_function(plot_setup.get_shift())
    support_function = get_support_function(plot_setup.get_mask())

    for f in files:
        img = spimage.sp_image_read(f,0)
        support_function(img)
        img = sp_image_shift(img)
        spimage.sp_image_write(img,output_dir+"/"+f[:-2]+"png",plot_setup.get_color())
        spimage.sp_image_free(img)
示例#6
0
文件: to_png.py 项目: ekeberg/Scripts
def to_png(*arguments):
    color,shift_flag,support_flag = evaluate_arguments(arguments)
    files = read_files()

    shift_function = get_shift_function(shift_flag)
    support_function = get_support_function(support_flag)

    for f in files:
        img = spimage.sp_image_read(f,0)
        support_function(img)
        img = sp_image_shift(img)
        spimage.sp_image_write(img,f[:-2]+"png",color)
        spimage.sp_image_free(img)
示例#7
0
def find_center_blurred(img, msk, x0=0, y0=0, threshold=None, blur_radius=4., dmax=5):
    """
    Find the center using blurred version of 'pixelwise' method.

    usage: 
    ======
    x,y = find_center_blurred(img, msk, x0=0, y0=0, threshold=None, blur_radius=4, dmax=5)
    """
    if threshold is None: threshold = img.min()
    I = spimage.sp_image_alloc(img.shape[1],img.shape[0],1)
    I.image[:] = img * (img >= threshold)
    I.mask[:] = msk[:]
    I.detector.image_center[:] = np.array([center_to_pos(x0,img.shape[1]),
                                           center_to_pos(y0,img.shape[0]), 0 ])
    kernel = spimage.sp_gaussian_kernel(float(blur_radius),int(blur_radius*8+1),int(blur_radius*8+1),1)
    c = spimage.sp_image_convolute_with_mask(I,kernel,np.array([1,1,1]).astype(np.int32))
    ds = spimage.sp_image_alloc(int(img.shape[1]/4),int(img.shape[0]/4),1)
    ds.image[:] = c.image[:-3:4,:-3:4]
    ds.mask[:] = c.mask[:-3:4,:-3:4]
    ds.detector.image_center[:] = c.detector.image_center[:] / 4.0
    spimage.sp_find_center_refine_minimal_mask(ds, int(1+dmax/4), 0)
    c.detector.image_center[:] = ds.detector.image_center[:] * 4.0
    spimage.sp_image_free(ds)
    score = spimage.sp_find_center_refine_minimal_mask(c, 4, 0)
    x = pos_to_center(c.detector.image_center[0],img.shape[1])
    y = pos_to_center(c.detector.image_center[1],img.shape[0])
    spimage.sp_image_free(I)
    spimage.sp_image_free(kernel)
    spimage.sp_image_free(c)
    return (x,y,score)
示例#8
0
def find_center_blurred(img, msk, x0=0, y0=0, threshold=None, blur_radius=4., dmax=5):
    """
    Find the center using blurred version of 'pixelwise' method.

    usage: 
    ======
    x,y = find_center_blurred(img, msk, x0=0, y0=0, threshold=None, blur_radius=4, dmax=5)
    """
    if threshold is None: threshold = img.min()
    I = spimage.sp_image_alloc(img.shape[1],img.shape[0],1)
    I.image[:] = img * (img >= threshold)
    I.mask[:] = msk[:]
    I.detector.image_center[:] = np.array([center_to_pos(x0,img.shape[1]),
                                           center_to_pos(y0,img.shape[0]), 0 ])
    kernel = spimage.sp_gaussian_kernel(float(blur_radius),int(blur_radius*8+1),int(blur_radius*8+1),1)
    c = spimage.sp_image_convolute_with_mask(I,kernel,np.array([1,1,1]).astype(np.int32))
    ds = spimage.sp_image_alloc(img.shape[1]/4,img.shape[0]/4,1)
    ds.image[:] = c.image[:-3:4,:-3:4]
    ds.mask[:] = c.mask[:-3:4,:-3:4]
    ds.detector.image_center[:] = c.detector.image_center[:] / 4.0
    spimage.sp_find_center_refine_minimal_mask(ds, int(1+dmax/4), 0)
    c.detector.image_center[:] = ds.detector.image_center[:] * 4.0
    spimage.sp_image_free(ds)
    score = spimage.sp_find_center_refine_minimal_mask(c, 4, 0)
    x = pos_to_center(c.detector.image_center[0],img.shape[1])
    y = pos_to_center(c.detector.image_center[1],img.shape[0])
    spimage.sp_image_free(I)
    spimage.sp_image_free(kernel)
    spimage.sp_image_free(c)
    return (x,y,score)
def pnccd_to_image(infile, outfile):
    try:
        f = h5py.File(infile)
    except:
        raise IOError("Can't read %s. It may not be a pnCCD file." % filename)

    i1 = f.keys().index("data")
    i2 = f.values()[i1].keys().index("data1")

    data = f.values()[i1].values()[i2].value

    img = spimage.sp_image_alloc(pylab.shape(data)[0], pylab.shape(data)[1], 1)
    img.image[:, :] = data[:, :]
    spimage.sp_image_write(img, outfile, 0)
    spimage.sp_image_free(img)
 def _init_initial_support(self):
     if not self._initial_support_dirty:
         self._log("Initial support already initialised.","DEBUG")
         return
     for img in [self._sp_initial_support,self._sp_initial_support_sh]:
         if img is not None:
             spimage.sp_image_free(img)
     A = self._amplitudes
     if len(A.shape) == 2:
         self._sp_initial_support = spimage.sp_image_alloc(self._Ny,self._Nx,1)
         if "radius" in self._initial_support_config or "area" in self._initial_support_config:
             X,Y = np.meshgrid(np.arange(self._Nx),np.arange(self._Ny))
             X = X-(self._Nx-1)/2.
             Y = Y-(self._Ny-1)/2.
             R = np.sqrt(X**2 + Y**2)
             self._phaser_dirty = True
             if "radius" in self._initial_support_config:
                 r = self._initial_support_config["radius"]
             else:
                 r = np.sqrt( self._initial_support_config["area"] * self._Nx * self._Ny / np.pi )
             self._sp_initial_support.image[:] = np.float32(np.fft.fftshift(R) < r)
         else:
             self._phaser_dirty = True
             S = self._initial_support_config["support_mask"]
             self._sp_initial_support.image[:] = np.float32(S)
             self._initial_support_dirty = False
             self._log("Initial support initialised.","DEBUG")
     if len(A.shape) == 3:
         self._sp_initial_support = spimage.sp_image_alloc(self._Nz, self._Ny,self._Nx)
         if "radius" in self._initial_support_config or "area" in self._initial_support_config:
             X,Y,Z = np.meshgrid(np.arange(self._Nx),np.arange(self._Ny),np.arange(self._Nz))
             X = X-(self._Nx-1)/2.
             Y = Y-(self._Ny-1)/2.
             Z = Z-(self._Nz-1)/2.
             R = np.sqrt(X**2 + Y**2 + Z**2)
             self._phaser_dirty = True
             if "radius" in self._initial_support_config:
                 r = self._initial_support_config["radius"]
             else:
                 r = np.sqrt( self._initial_support_config["area"] * self._Nx * self._Ny *  self._Nz / np.pi )
             self._sp_initial_support.image[:] = np.float32(np.fft.fftshift(R) < r)
         else:
             self._phaser_dirty = True
             S = self._initial_support_config["support_mask"]
             self.sep_initial_support.image[:] = np.float32(S)
             self._initial_support_dirty = False
             self._log("Initial support initialised.","DEBUG")
示例#11
0
def center_image(filename, outfile, sigma=3):
    """Finds a localized strong object and puts it in the center. The
    sigma variable describes the size of the object"""
    print("foo")
    if not os.path.isfile(filename):
        raise IOError("Can not find file {0}".format(filename))
    img = spimage.sp_image_read(filename, 0)
    x = (numpy.arange(img.image.shape[0], dtype='float64') -
         img.image.shape[0] / 2. + 0.5)
    y = (numpy.arange(img.image.shape[1], dtype='float64') -
         img.image.shape[1] / 2. + 0.5)
    z = (numpy.arange(img.image.shape[2], dtype='float64') -
         img.image.shape[2] / 2. + 0.5)
    kernel = numpy.exp(-(x[:, numpy.newaxis, numpy.newaxis]**2 +
                         y[numpy.newaxis, :, numpy.newaxis]**2 +
                         y[numpy.newaxis, numpy.newaxis, :]**2) / 2.0 /
                       sigma**2)

    img_ft = numpy.fft.fft2(numpy.fft.fftshift(img.image))
    kernel_ft = numpy.fft.fft2(numpy.fft.fftshift(kernel))
    kernel_ft *= numpy.conj(img_ft)
    bt = numpy.fft.ifft2(kernel_ft)

    min_v = 0.
    min_x = 0
    min_y = 0
    min_z = 0
    for x in range(bt.shape[0]):
        for y in range(bt.shape[1]):
            for z in range(bt.shape[2]):
                if abs(bt[z, y, x]) > min_v:
                    min_v = abs(bt[z, y, x])
                    min_x = x
                    min_y = y
                    min_z = z
    print(min_x, min_y, min_z)
    spimage.sp_image_translate(img, -(-min_z + bt.shape[0] // 2),
                               -(-min_y + bt.shape[1] // 2),
                               -(-min_x + bt.shape[2] // 2),
                               spimage.SP_TRANSLATE_WRAP_AROUND)
    shift = img

    spimage.sp_image_write(shift, outfile, 0)
    spimage.sp_image_free(img)
示例#12
0
def find_center_pixelwise_fast(img, msk, x0=0, y0=0, dmax=5, rmax=None):
    """
    Find center of diffraction pattern using a pixelwise comparison of centry-symmetric pixels.

    This is a faster C implementation.

    usage:
    ======
    x,y = find_center_pixelwise_fast(img, msk, x0, y0, dmax=5, rmax=None)
    """
    if rmax is not None: msk &= (spimage.rgrid(msk.shape, (x0,y0)) < rmax)
    I = spimage.sp_image_alloc(int(np.ceil(img.shape[1])), int(np.ceil(img.shape[0])), 1)
    I.image[:] = img
    I.mask[:]  = msk
    I.detector.image_center[:] = np.array([center_to_pos(x0,img.shape[1]), center_to_pos(y0,img.shape[0]), 0 ])
    success = spimage.sp_find_center_refine(I, dmax, 0, None)
    x = pos_to_center(I.detector.image_center[0],img.shape[1])
    y = pos_to_center(I.detector.image_center[1],img.shape[0])
    spimage.sp_image_free(I)
    return (x,y,success)
示例#13
0
def find_center_pixelwise_fast(img, msk, x0=0, y0=0, dmax=5, rmax=None):
    """
    Find center of diffraction pattern using a pixelwise comparison of centry-symmetric pixels.

    This is a faster C implementation.

    usage:
    ======
    x,y = find_center_pixelwise_fast(img, msk, x0, y0, dmax=5, rmax=None)
    """
    if rmax is not None: msk &= (spimage.rgrid(msk.shape, (x0,y0)) < rmax)
    I = spimage.sp_image_alloc(int(np.ceil(img.shape[1])), int(np.ceil(img.shape[0])), 1)
    I.image[:] = img
    I.mask[:]  = msk
    I.detector.image_center[:] = np.array([center_to_pos(x0,img.shape[1]), center_to_pos(y0,img.shape[0]), 0 ])
    success = spimage.sp_find_center_refine(I, dmax, 0, None)
    x = pos_to_center(I.detector.image_center[0],img.shape[1])
    y = pos_to_center(I.detector.image_center[1],img.shape[0])
    spimage.sp_image_free(I)
    return (x,y,success)
 def _init_amplitudes(self):
     if not self._amplitudes_dirty:
         self._log("Amplitudes already initialised.","DEBUG")
         return
     A = self._amplitudes
     self._Nx = A.shape[1]
     self._Ny = A.shape[0]
     if self._mask is not None:
         M = self._mask.copy()
     else:
         M = np.ones(shape=A.shape,dtype="bool")
     for img in [self._sp_amplitudes]:
         if img is not None:
             spimage.sp_image_free(img)
     self._sp_amplitudes = spimage.sp_image_alloc(A.shape[0],A.shape[1],1)
     self._sp_amplitudes.image[:,:] = np.float32(A[:,:])
     self._sp_amplitudes.mask[:,:] = np.int32(M[:,:])
     self._sp_amplitudes.scaled = 1
     self._sp_amplitudes.phased = 0
     self._amplitudes_dirty = False
     self._log("Amplitudes initialised.","DEBUG")
 def _init_amplitudes(self):
     if not self._amplitudes_dirty:
         self._log("Amplitudes already initialised.","DEBUG")
         return
     A = self._amplitudes
     if len(A.shape) == 2:
         self._Nx = A.shape[1]
         self._Ny = A.shape[0]
         if self._mask is not None:
             M = self._mask.copy()
         else:
             M = np.ones(shape=A.shape,dtype="bool")
         for img in [self._sp_amplitudes]:
             if img is not None:
                 spimage.sp_image_free(img)
         self._sp_amplitudes = spimage.sp_image_alloc(A.shape[0],A.shape[1],1)
         self._sp_amplitudes.image[:,:] = np.float32(A[:,:])
         self._sp_amplitudes.mask[:,:] = np.int32(M[:,:])
         self._sp_amplitudes.scaled = 1
         self._sp_amplitudes.phased = 0
         self._amplitudes_dirty = False
         self._log("Amplitudes initialised.","DEBUG")
     if len(A.shape) == 3:
         self._Nx = A.shape[2]
         self._Ny = A.shape[1]
         self._Nz = A.shape[0]
         if self._mask is not None:
             M = self._mask.copy()
         else:
             M = np.ones(shape=A.shape,dtype="bool")
         for img in [self._sp_amplitudes]:
             if img is not None:
                 spimage.sp_image_free(img)
         self._sp_amplitudes = spimage.sp_image_alloc(A.shape[0],A.shape[1],A.shape[2])
         self._sp_amplitudes.image[:,:,:] = np.float32(A[:,:,:])
         self._sp_amplitudes.mask[:,:,:] = np.int32(M[:,:,:])
         self._sp_amplitudes.scaled = 1
         self._sp_amplitudes.phased = 0
         self._amplitudes_dirty = False
         self._log("Amplitudes initialised.","DEBUG")
示例#16
0
def crop_image(in_file, out_file, side, center=None):
    """Function to crop an h5 image and pad with zeros around it"""

    img = spimage.sp_image_read(in_file, 0)

    if not center:
        center = img.detector.image_center[:2]

    shifted = 0
    if img.shifted:
        shifted = 1
        img = spimage.sp_image_shift(img)

    print "shifted = ", shifted

    # cropped = spimage.rectangle_crop(img,lowX,lowY,highX,highY)
    cropped = spimage.sp_image_alloc(side, side, 1)
    cropped.image[:, :] = image_manipulation.crop_and_pad(img.image, center, side)
    cropped.mask[:, :] = image_manipulation.crop_and_pad(img.mask, center, side)

    print "did crop"

    if shifted:
        cropped = spimage.sp_image_shift(cropped)

    print "shifted (or not)"

    print "write ", out_file

    # print "orientation = ", cropped.detector.orientation
    # print spimage.sp_3matrix_get(cropped.detector.orientation,0,0,0)

    spimage.sp_image_write(cropped, out_file, 16)

    spimage.sp_image_free(img)
    spimage.sp_image_free(cropped)

    print "end"
示例#17
0
 def process(self, f):
     img = spimage.sp_image_read(f, 0)
     img = self.process_function(img)
     output_file = self.out_dir + "/" + f[:-2] + "png"
     spimage.sp_image_write(img, output_file, self.color)
     spimage.sp_image_free(img)
示例#18
0
def real_space_residual_all_iterations(reference_file=None,
                                       support_file=None,
                                       iteration=None,
                                       mode='absolute',
                                       normalize_ref_to_model=False,
                                       skip='None',
                                       model_cf=None):
    if mode == 'absolute': f = np.absolute
    elif mode == 'angle': f = np.angle
    elif mode == 'real': f = np.real
    elif mode == 'imag': f = np.imag

    if os.getcwd().startswith('/mnt'):
        models = [
            i + '/output_mnt/' for i in os.listdir('.')
            if i.startswith('run_') and not i.startswith(skip)
        ]
    else:
        models = [
            i + '/output/' for i in os.listdir('.')
            if i.startswith('run_') and not i.startswith(skip)
        ]
    models.sort()
    files_dir_0 = models[0]
    print files_dir_0
    if iteration == None:
        iteration = return_last_iteration_integer(files_dir_0)
        print iteration

    if support_file != None:
        support_sp = spimage.sp_image_read(support_file, 0)
        support_arr = real(support_sp.image[:])
    elif model_cf != None:
        prtf_dir = [d for d in os.listdir('.') if d.startswith('prtf')]
        avg_model = f(
            spimage.sp_image_read(
                os.path.join(prtf_dir[0], 'PRTF-avg_image.h5'), 0).image[:])
        support_arr = np.zeros_like(avg_model)
        support_arr[(avg_model / avg_model.max()) >= model_cf] = 1
        print 'using {} pixels'.format(np.sum(support_arr))

    else:
        print models[0]
        support_sp = spimage.sp_image_read(
            files_dir_0 + 'support_%04d.h5' % iteration, 0)
        support_arr = real(support_sp.image[:])

    if reference_file != None:
        reference_sp = spimage.sp_image_read(reference_file, 0)
        reference = f(reference_sp.image[:])

    else:
        reference = support_arr.copy()
    rscs = []
    for m in models:
        try:
            model_sp = spimage.sp_image_read(m + 'model_%04d.h5' % iteration,
                                             0)
            model = f(model_sp.image[:])
            print m
            rscs.append(
                stuff.real_space_residual(reference,
                                          model,
                                          support=support_arr,
                                          normalize=True))
            spimage.sp_image_free(model_sp)
            del model
        except AttributeError:
            print 'Error: {} does not exist'.format(m)
    return rscs
示例#19
0
 def shift_function(img):
     ret = spimage.sp_image_shift(img)
     spimage.sp_image_free(img)
     return ret
示例#20
0
def to_png(*arguments):
    if len(arguments) <= 0:
        print("""
    This program converts all h5 files in the curren directory to png.
    Usage:  python_script_new_to_png [colorscale]

    Colorscales:
    Jet
    Gray
    PosNeg
    InvertedPosNeg
    Phase
    InvertedPhase
    Log (can be combined with the others)
    Shift (can be combined with the others)
    Support

    """)
        return
    elif not (isinstance(arguments, list) or isinstance(arguments, tuple)):
        print("function to_png takes must have a list or string input")
        return

    files = os.listdir('.')

    expr = re.compile('.h5$')
    h5_files = list(filter(expr.search, files))

    expr = re.compile('.png$')
    png_files = list(filter(expr.search, files))

    files = [f for f in h5_files if f[:-2]+"png" not in png_files]
    files.sort()

    print("Converting %d files" % len(files))

    log_flag = 0
    shift_flag = 0
    support_flag = 0
    color = 16

    for flag in arguments:
        if flag == 'PosNeg':
            color = 8192
        elif flag == 'InvertedPosNeg':
            color = 16384
        elif flag == 'Phase':
            color = 256
        elif flag == 'InvertedPhase':
            color = 4096
        elif flag == 'Jet':
            color = 16
        elif flag == 'Gray':
            color = 1
        elif flag == 'Log':
            log_flag = 1
        elif flag == 'Shift':
            shift_flag = 1
        elif flag == 'Support':
            support_flag = 1
        else:
            print("unknown flag %s" % flag)

    if log_flag == 1:
        color += 128

    # for f in files:
    #     img = spimage.sp_image_read(f[:-1],0)

    if shift_flag:
        def shift_function(img):
            ret = spimage.sp_image_shift(img)
            spimage.sp_image_free(img)
            return ret
    else:
        def shift_function(img):
            return img

    if support_flag:
        for f in files:
            img = spimage.sp_image_read(f, 0)
            spimage.sp_image_mask_to_image(img, img)
            img = shift_function(img)
            spimage.sp_image_write(img, f[:-2]+"png", color)
            spimage.sp_image_free(img)
    else:
        for f in files:
            img = spimage.sp_image_read(f, 0)
            img = shift_function(img)
            spimage.sp_image_write(img, f[:-2]+"png", color)
            spimage.sp_image_free(img)
示例#21
0
文件: to_png.py 项目: ekeberg/Scripts
 def process(self, f):
     #for f in files:
     img = spimage.sp_image_read(f,0)
     img = self.process_function(img)
     spimage.sp_image_write(img,f[:-2]+"png",self.color)
     spimage.sp_image_free(img)
示例#22
0
def to_png(*arguments):
    if len(arguments) <= 0:
        print """
    This program converts all h5 files in the curren directory to png.
    Usage:  python_script_new_to_png [colorscale]

    Colorscales:
    Jet
    Gray
    PosNeg
    InvertedPosNeg
    Phase
    InvertedPhase
    Log (can be combined with the others)
    Shift (can be combined with the others)
    Support

    """
        return
    elif not (isinstance(arguments,list) or isinstance(arguments,tuple)):
        print "function to_png takes must have a list or string input"
        return


    #l = os.popen('ls').readlines()
    l = os.listdir('.')

    expr = re.compile('.h5$')
    h5_files = filter(expr.search,l)

    expr = re.compile('.png$')
    png_files = filter(expr.search,l)

    files = [f for f in h5_files if f[:-2]+"png" not in png_files]
    files.sort()

    print "Converting %d files" % len(files)

    log_flag = 0
    shift_flag = 0
    support_flag = 0
    color = 16

    for flag in arguments:
        if flag == 'PosNeg':
            color = 8192
        elif flag == 'InvertedPosNeg':
            color = 16384
        elif flag == 'Phase':
            color = 256
        elif flag == 'InvertedPhase':
            color = 4096
        elif flag == 'Jet':
            color = 16
        elif flag == 'Gray':
            color = 1
        elif flag == 'Log':
            log_flag = 1
        elif flag == 'Shift':
            shift_flag = 1
        elif flag == 'Support':
            support_flag = 1
        else:
            print "unknown flag %s" % flag

    if log_flag == 1:
        color += 128

    # for f in files:
    #     img = spimage.sp_image_read(f[:-1],0)

    def shift_function(img):
        return img

    if shift_flag:
        def shift_function(img):
            ret = spimage.sp_image_shift(img)
            spimage.sp_image_free(img)
            return ret

    if support_flag:
        for f in files:
            img = spimage.sp_image_read(f,0)
            spimage.sp_image_mask_to_image(img,img)
            img = shift_function(img)
            spimage.sp_image_write(img,f[:-2]+"png",color)
            spimage.sp_image_free(img)
    else:
        for f in files:
            img = spimage.sp_image_read(f,0)
            img = shift_function(img)
            spimage.sp_image_write(img,f[:-2]+"png",color)
            spimage.sp_image_free(img)
示例#23
0
文件: to_png.py 项目: ekeberg/Scripts
 def shift_function(img):
     ret = spimage.sp_image_shift(img)
     spimage.sp_image_free(img)
     return ret
示例#24
0
 def process(self, f):
     img = spimage.sp_image_read(f,0)
     img = self.process_function(img)
     spimage.sp_image_write(img,self.out_dir+"/"+f[:-2]+"png",self.color)
     spimage.sp_image_free(img)
示例#25
0
def prtf(images_rs,supports,translate=True,enantio=True,full_out=False):
    """
    NOTE: For using the enantio option, the images need to be centered in fourier space (no phase ramp in real space)
    """
    S = images_rs.shape
    s = list(S)
    N = s.pop(0)
    s = tuple(s)

    image0_rs = images_rs[0]
    image0_fs = numpy.fft.fftn(image0_rs)

    sp_image0_rs = numpy_array_to_image(image0_rs,supports[0])
    sp_image0_fs = numpy_array_to_image(image0_fs)

    sp_amp_fs = spimage.sp_image_duplicate(sp_image0_fs,spimage.SP_COPY_ALL)
    spimage.sp_image_dephase(sp_amp_fs)

    spimage.sp_image_free(sp_image0_rs)
    spimage.sp_image_free(sp_image0_fs)

    sum_fs = image0_fs.copy()
    sum_fs[abs(sum_fs) > 0.] /= abs(sum_fs[abs(sum_fs) > 0.])

    sp_sum_fs = numpy_array_to_image(sum_fs)

    zeros = numpy.zeros(shape=s,dtype="int")
    zeros[abs(sum_fs) <= 0.] = 1

    sp_avg_img = numpy_array_to_image(image0_rs)
    avg_msk = numpy.zeros(shape=s,dtype="float")
    
    images_rs_super = numpy.zeros(shape=S,dtype="complex128")
    images_rs_super[0,:] = image0_rs[:]
    masks_rs_super = numpy.zeros(shape=S,dtype="bool")
    masks_rs_super[0,:] = supports[0,:]

    for i,img,sup in zip(range(1,N),images_rs[1:],supports[1:]):
        # Initialize image
        sp_img = numpy_array_to_image(img,sup)

        # Translate and enantio matching
        if translate:
            spimage.sp_image_superimpose(sp_avg_img,sp_img, spimage.SpEnantiomorph if enantio else 0)
            spimage.sp_image_phase_match(sp_avg_img,sp_img,2)
        spimage.sp_image_add(sp_avg_img,sp_img)

        if sp_img.mask.sum() > 0:
            avg_msk[sp_img.mask == 0] += 1

        # Cache image and support
        images_rs_super[i,:] = sp_img.image[:]
        masks_rs_super[i,:] = sp_img.mask[:]
        
        # Add amplitudes
        sp_tmp = spimage.sp_image_fftw3(sp_img)
        sp_tmpamp = spimage.sp_image_duplicate(sp_tmp,spimage.SP_COPY_ALL)
        spimage.sp_image_dephase(sp_tmpamp);
        spimage.sp_image_add(sp_amp_fs,sp_tmpamp)
        
        # Count zeros
        positive = abs(sp_tmp.image) > 0.
        sp_tmp.image[positive] /= abs(sp_tmp.image)[positive]
        zeros += (positive == False)
        
        spimage.sp_image_add(sp_sum_fs,sp_tmp)
        
        spimage.sp_image_free(sp_img)
        spimage.sp_image_free(sp_tmp)
        spimage.sp_image_free(sp_tmpamp)
  
    sp_prtf = spimage.sp_image_duplicate(sp_sum_fs,spimage.SP_COPY_DATA|spimage.SP_COPY_MASK)
    sp_prtf.image[:] /= N
    sp_prtf.image[zeros > 0] = 0.
    spimage.sp_image_dephase(sp_prtf)

    avg_img = sp_avg_img.image[:].copy()
    avg_sup = avg_msk > 0
    prtf = abs(sp_prtf.image[:]).copy()
    prtf = numpy.fft.fftshift(prtf)

    for sp_i in [sp_prtf,sp_avg_img,sp_amp_fs,sp_sum_fs]:
        spimage.sp_image_free(sp_i)  
      
    out = {}
    out["prtf"] = prtf
    out["super_image"] = avg_img
    if full_out:
        out["prtf_r"] = spimage.radial_mean(prtf,cx=s[1]/2,cy=s[0]/2)
        out["super_mask"] = avg_sup
        out["images"] = images_rs_super
        out["masks"] = masks_rs_super
    return out
示例#26
0
def prtf(images_rs, supports, translate=True, enantio=True, full_out=False):
    """
    NOTE: For using the enantio option, the images need to be centered in fourier space (no phase ramp in real space)
    """
    S = images_rs.shape
    s = list(S)
    N = s.pop(0)
    s = tuple(s)

    image0_rs = images_rs[0]
    image0_fs = numpy.fft.fftn(image0_rs)

    sp_image0_rs = numpy_array_to_image(image0_rs, supports[0])
    sp_image0_fs = numpy_array_to_image(image0_fs)

    sp_amp_fs = spimage.sp_image_duplicate(sp_image0_fs, spimage.SP_COPY_ALL)
    spimage.sp_image_dephase(sp_amp_fs)

    spimage.sp_image_free(sp_image0_rs)
    spimage.sp_image_free(sp_image0_fs)

    sum_fs = image0_fs.copy()
    sum_fs[abs(sum_fs) > 0.] /= abs(sum_fs[abs(sum_fs) > 0.])

    sp_sum_fs = numpy_array_to_image(sum_fs)

    zeros = numpy.zeros(shape=s, dtype="int")
    zeros[abs(sum_fs) <= 0.] = 1

    sp_avg_img = numpy_array_to_image(image0_rs)
    avg_msk = numpy.zeros(shape=s, dtype="float")

    images_rs_super = numpy.zeros(shape=S, dtype="complex128")
    images_rs_super[0, :] = image0_rs[:]
    masks_rs_super = numpy.zeros(shape=S, dtype="bool")
    masks_rs_super[0, :] = supports[0, :]

    for i, img, sup in zip(range(1, N), images_rs[1:], supports[1:]):
        # Initialize image
        sp_img = numpy_array_to_image(img, sup)

        # Translate and enantio matching
        if translate:
            spimage.sp_image_superimpose(
                sp_avg_img, sp_img, spimage.SpEnantiomorph if enantio else 0)
            spimage.sp_image_phase_match(sp_avg_img, sp_img, 2)
        spimage.sp_image_add(sp_avg_img, sp_img)

        if sp_img.mask.sum() > 0:
            avg_msk[sp_img.mask == 0] += 1

        # Cache image and support
        images_rs_super[i, :] = sp_img.image[:]
        masks_rs_super[i, :] = sp_img.mask[:]

        # Add amplitudes
        sp_tmp = spimage.sp_image_fftw3(sp_img)
        sp_tmpamp = spimage.sp_image_duplicate(sp_tmp, spimage.SP_COPY_ALL)
        spimage.sp_image_dephase(sp_tmpamp)
        spimage.sp_image_add(sp_amp_fs, sp_tmpamp)

        # Count zeros
        positive = abs(sp_tmp.image) > 0.
        sp_tmp.image[positive] /= abs(sp_tmp.image)[positive]
        zeros += (positive == False)

        spimage.sp_image_add(sp_sum_fs, sp_tmp)

        spimage.sp_image_free(sp_img)
        spimage.sp_image_free(sp_tmp)
        spimage.sp_image_free(sp_tmpamp)

    sp_prtf = spimage.sp_image_duplicate(
        sp_sum_fs, spimage.SP_COPY_DATA | spimage.SP_COPY_MASK)
    sp_prtf.image[:] /= N
    sp_prtf.image[zeros > 0] = 0.
    spimage.sp_image_dephase(sp_prtf)

    avg_img = sp_avg_img.image[:].copy()
    avg_sup = avg_msk > 0
    prtf = abs(sp_prtf.image[:]).copy()
    prtf = numpy.fft.fftshift(prtf)

    for sp_i in [sp_prtf, sp_avg_img, sp_amp_fs, sp_sum_fs]:
        spimage.sp_image_free(sp_i)

    out = {}
    out["prtf"] = prtf
    out["super_image"] = avg_img
    if full_out:
        out["prtf_r"] = spimage.radial_mean(prtf, cx=s[1] / 2, cy=s[0] / 2)
        out["super_mask"] = avg_sup
        out["images"] = images_rs_super
        out["masks"] = masks_rs_super
    return out
示例#27
0
# img.image[img.image < 0.0] = 0.0

options = ["shift", "log", "mask"]

for o in sys.argv:
    if o in options:
        if o.lower() == "shift":
            shift = True
        if o.lower() == "log":
            log = True
        if o.lower() == "mask":
            plot_mask = True

if shift:
    img_s = spimage.sp_image_shift(img)
    spimage.sp_image_free(img)
    img = img_s

if plot_mask:
    plot_array = img.mask
else:
    plot_array = abs(img.image)

if log:
    s = mlab.pipeline.scalar_field(log10(0.001 * max(plot_array.flatten()) + plot_array))
else:
    s = mlab.pipeline.scalar_field(plot_array)

# mlab.figure(size=(1000,900))

mlab.pipeline.image_plane_widget(s, plane_orientation="x_axes", slice_index=shape(img.image)[0] / 2)