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) 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) if shifted: cropped = spimage.sp_image_shift(cropped) spimage.sp_image_write(cropped, out_file, 16) spimage.sp_image_free(img) spimage.sp_image_free(cropped) print("end")
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 crop_image(in_file, out_file, sideX, sideY = 0): if sideY == 0: sideY = sideX try: img = spimage.sp_image_read(in_file,0) except: print "Error: %s is not a readable .h5 file\n" % in_file exit(1) shifted = 0 if img.shifted: shifted = 1 img = spimage.sp_image_shift(img) print "shifted = ", shifted lowX = img.detector.image_center[0]-(sideX/2.0-0.5) highX = img.detector.image_center[0]+(sideX/2.0-0.5) lowY = img.detector.image_center[1]-(sideY/2.0-0.5) highY = img.detector.image_center[1]+(sideY/2.0-0.5) print lowX, " ", highX print lowY, " ", highY if lowX != pylab.floor(lowX): lowX = int(pylab.floor(lowX)) highX = int(pylab.floor(highX)) img.detector.image_center[0] -= 0.5 else: lowX = int(lowX) highX = int(highX) if lowY != pylab.floor(lowY): lowY = int(pylab.floor(lowY)) highY = int(pylab.floor(highY)) img.detector.image_center[1] -= 0.5 else: lowY = int(lowY) highY = int(highY) cropped = spimage.rectangle_crop(img,lowX,lowY,highX,highY) 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) try: spimage.sp_image_write(cropped,out_file,16) except: print "Error: can not write to %s\n" % out_file print "end"
def prep_emc_output_for_phasing(input_file, output_file, corner_to_zero=False): "Sets all negative values in image to 0 and create a rectangular mask" img = spimage.sp_image_read(input_file, 0) #set all negative values to 0: img.image[:, :, :] = img.image.clip(0) #set corners of mask to 1: r_array = stuff.r_array_3D(img.image.shape[0]) img.mask[r_array > img.image.shape[0] / 2. + 0.5] = 1 if corner_to_zero: img.image[r_array > img.image.shape[0]] = 0. spimage.sp_image_write(img, output_file, 0)
def to_png(input_dir, output_dir, plot_setup): files = read_files(input_dir) support_function = get_support_function(plot_setup.get_mask()) for f in files: img = spimage.sp_image_read(f, 0) support_function(img) img = spimage.sp_image_shift(img) output_file = output_dir + "/" + f[:-2] + "png" spimage.sp_image_write(img, output_file, plot_setup.get_color()) spimage.sp_image_free(img)
def mask_center_and_negatives(img_file_name, radius, output_file_name, save_file=True): """Creates a new mask around the center with given radius as well as masking out regions with negative values in the image.""" msk = mask_center(img_file_name, radius, output_file_name, save_file=False) img = spimage.sp_image_read(img_file_name, 0) msk.mask[real(img.image) < 0.] = 0 if save_file: spimage.sp_image_write(msk, output_file_name, 0) else: return (msk)
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)
def image_to_png(in_filename, out_filename, colorscale, shift): try: img = spimage.sp_image_read(in_filename,0) except: raise TypeError("%s is not a readable file" % in_filename) if shift == 1: img = spimage.sp_image_shift(img) try: spimage.sp_image_write(img,out_filename,colorscale) except: raise TypeError("Can not write %s" % out_filename)
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)
def image_to_png(in_filename, out_filename, colorscale, shift): try: img = spimage.sp_image_read(in_filename, 0) except IOError: raise TypeError(f"{in_filename} is not a readable file") if shift == 1: img = spimage.sp_image_shift(img) try: spimage.sp_image_write(img, out_filename, colorscale) except IOError: raise TypeError(f"Can not write {out_filename}")
def shift_image(in_file,out_file = 0): try: img = spimage.sp_image_read(in_file,0) except: raise IOError("Can't read %s" % in_file) img_s = spimage.sp_image_shift(img) if out_file == 0: out_file = in_file try: spimage.sp_image_write(img_s,out_file,0) except: print "Error: Can not write to %s" % out_file
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 shift_image(in_file, out_file=0): try: img = spimage.sp_image_read(in_file, 0) except IOError: raise IOError(f"Can't read {in_file}") img_s = spimage.sp_image_shift(img) if out_file == 0: out_file = in_file try: spimage.sp_image_write(img_s, out_file, 0) except IOError: print(f"Error: Can not write to {out_file}")
def split_pnccd(filename): f = h5py.File(filename) i1 = f.keys().index('data') i2 = f.values()[i1].keys().index('data1') i2 = f.values()[i1].keys().index('data1') data2 = f.values()[i1].values()[i2].value data2_1 = spimage.sp_image_alloc(data2.shape[1]/2,data2.shape[0],1) data2_2 = spimage.sp_image_alloc(data2.shape[1]/2,data2.shape[0],1) data2_1.image[:,:] = data2[:,:(data2.shape[1]/2)] data2_2.image[:,:] = data2[:,(data2.shape[1]/2):] spimage.sp_image_write(data2_1,filename[:-3]+"_part1.h5",0) spimage.sp_image_write(data2_2,filename[:-3]+"_part2.h5",0)
def mask_center(img_file_name, radius, output_file_name=None, save_file=True): """Create a new mask around the center with given radius""" img = spimage.sp_image_read(img_file_name, 0) r_array = stuff.r_array_3D(img.image.shape[0]) img.mask[r_array < radius] = 0 img.mask[r_array > radius] = 1 new_mask = spimage.sp_image_alloc(*np.shape(img.mask)) new_mask.mask[:, :, :] = img.mask new_mask.image[:, :, :] = img.image new_mask.shifted = img.shifted new_mask.scaled = img.scaled new_mask.detector = img.detector if save_file: spimage.sp_image_write(new_mask, output_file_name, 0) else: return (new_mask)
def add_new_mask(img_file_name, new_mask_file_name, output_file_name, imgtimesmask=False): img = spimage.sp_image_read(img_file_name, 0) new_mask = spimage.sp_image_read(new_mask_file_name, 0) new_img = spimage.sp_image_alloc(*shape(img.image)) new_img.image[:, :, :] = img.image new_img.shifted = img.shifted new_img.scaled = img.scaled new_img.detector = img.detector new_img.mask[:, :, :] = new_mask.mask spimage.sp_image_write(new_img, output_file_name, 0) if imgtimesmask: new_img.image[:, :, :] = img.image * new_mask.mask spimage.sp_image_write(new_img, 'imgtimesmask.h5', 0)
def shift_image(in_file,out_file = 0): try: img = spimage.sp_image_read(in_file,0) except: print "Error: Can not read image %s" % in_file return img_s = spimage.sp_image_shift(img) if out_file == 0: out_file = in_file try: spimage.sp_image_write(img_s,out_file,0) except: print "Error: Can not write to %s" % out_file
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)
def add_mask(path, number_of_files, output_file): """Reads in files in paths, outputs h5 file output_file with accumulative mask from input images saved in both image and mask""" imgs = [ os.path.join(path, i) for i in os.listdir(path) if i.endswith('.h5') ] for img_file in imgs[:number_of_files]: img = spimage.sp_image_read(img_file, 0) try: msk_array = msk_array + img.mask except NameError: msk_array = img.mask msk_array[msk_array < msk_array.max()] = 0 msk_array[msk_array != 0] = 1 new = spimage.sp_image_alloc( numpy.shape(img.image)[0], numpy.shape(img.image)[1], 1) new.mask[:, :] = msk_array new.image[:, :] = msk_array spimage.sp_image_write(new, output_file, 0)
def calc_average_img(r2, r1=0, r_skip=None, iteration=None): rundir_range = range(r1, r2) if r_skip != None: for i in r_skip: rundir_range.remove(i) fail = 0 for r in rundir_range: run_dir = 'run_%04d' % r print run_dir if iteration == None: iteration = return_last_iteration_integer( '{r}/output_mnt/'.format(r=run_dir)) with h5py.File('{r}/output_mnt/fmodel_{i}.h5'.format( r=run_dir, i=iteration)) as f: try: added_real += f['real'][...] added_imag += f['imag'][...] except NameError: added_real = f['real'][...] added_imag = f['imag'][...] except KeyError: print 'fail' fail += 1 if r == r2 - 1: mask = f['mask'][:] added_real /= float(len(rundir_range) - fail) added_imag /= float(len(rundir_range) - fail) complex_fmodel = added_real + 1j * added_imag new = spimage.sp_image_alloc(*np.shape(added_real)) new.phased = 1 new.mask[:] = mask new.image[:] = complex_fmodel spimage.sp_image_write( new, 'avg_fmodel_runs_{i}_{j}_iteration{k}.h5'.format(i=r1, j=r2, k=iteration), 0) new.image[:, :, :] = fft.fftn(complex_fmodel) spimage.sp_image_write( new, 'avg_model_runs_{i}_{j}_iteration{k}.h5'.format(i=r1, j=r2, k=iteration), 0)
def calc_average_img_translated(r2, r1=0, r_skip=None, iteration=None, reference_model=None): rundir_range = range(r1, r2) if r_skip != None: for i in r_skip: rundir_range.remove(i) for r in rundir_range: run_dir = 'run_%04d' % r print run_dir if iteration == None: iteration = return_last_iteration_integer( '{r}/output_mnt/'.format(r=run_dir)) f = spimage.sp_image_read( '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=iteration), 0) if r == r1: if reference_model == None: ref = f else: ref = reference_model added_img = f.image[:] mask = f.mask[:] if r != r1: spimage.sp_image_superimpose(ref, f, 0) added_img += f.image[:] added_img /= float(len(rundir_range)) new = spimage.sp_image_alloc(*np.shape(added_img)) new.phased = 1 new.mask[:] = mask new.image[:] = added_img spimage.sp_image_write( new, 'avg_fmodel_runs_{i}_{j}_iteration{k}.h5'.format(i=r1, j=r2, k=iteration), 0) new.image[:, :, :] = fft.fftn(added_img) spimage.sp_image_write( new, 'avg_model_runs_{i}_{j}_iteration{k}.h5'.format(i=r1, j=r2, k=iteration), 0)
def slice_3D(fn, output_dir=''): #Takes 3 slices through the center along x,y and z from a 3D image and saves it as three new 2D images. img_3D = spimage.sp_image_read(fn, 0) dim = shape(img_3D.image)[0] img_2D = spimage.sp_image_alloc(dim, dim, 1) img_2D.shifted = img_3D.shifted img_2D.scaled = img_3D.scaled if img_3D.shifted == 0: s = dim / 2 else: s = 0 img_2D.image[:, :] = img_3D.image[s, :, :] img_2D.mask[:, :] = img_3D.mask[s, :, :] spimage.sp_image_write(img_2D, output_dir + fn.split('.')[0] + '_x_slice.h5', 0) img_2D.image[:, :] = img_3D.image[:, s, :] img_2D.mask[:, :] = img_3D.mask[:, s, :] spimage.sp_image_write(img_2D, output_dir + fn.split('.')[0] + '_y_slice.h5', 0) img_2D.image[:, :] = img_3D.image[:, :, s] img_2D.mask[:, :] = img_3D.mask[:, :, s] spimage.sp_image_write(img_2D, output_dir + fn.split('.')[0] + '_z_slice.h5', 0)
def calc_average_img(path, cutoff=None): if cutoff == None: run_folders = [] run_folders = select_by_error_cutoff(path, cutoff)['run'] for r in run_folders: img = spimage.sp_image_read( r + '/output_mnt/model_{n}.h5'.format(n=return_last_iteration_integer( os.path.join(r, 'output_mnt'))), 0) try: added_imgs = added_imgs + img.image except NameError: added_imgs = img.image avg_img = added_imgs / float(len(run_folders)) new = spimage.sp_image_alloc(*np.shape(img.image)) new.image[:, :, :] = avg_img spimage.sp_image_write( new, '{p}/average_final_model_{c}_{t}.h5'.format(p=path, c=cutoff, t=time.strftime('%Y%m%d')), 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"
spimage.sp_phaser_init_model(phaser, None, spimage.SpModelRandomPhases) spimage.sp_phaser_init_support(phaser, support, 0, 0) def run_it(number_of_iterations): spimage.sp_phaser_iterate(phaser, number_of_iterations) run_it(NUMBER_OF_ITERATIONS) phaser.algorithm = phase_alg_refine run_it(NUMBER_OF_REFINE_ITERATIONS) # Output data model = spimage.sp_phaser_model(phaser) support = spimage.sp_phaser_support(phaser) fmodel = spimage.sp_phaser_fmodel(phaser) spimage.sp_image_write(model, OUTPUT_DIR + "run_{}_model.h5".format(run_id), 0) spimage.sp_image_write(support, OUTPUT_DIR + "run_{}_support.h5".format(run_id), 0) spimage.sp_image_write(fmodel, OUTPUT_DIR + "run_{}_fmodel.h5".format(run_id), 0) ereal = spimage.sp_phaser_ereal(phaser) efourier = spimage.sp_phaser_efourier(phaser) filename = OUTPUT_DIR + '/run_{}_error.h5'.format(run_id) with h5py.File(filename, "w") as file_handle: file_handle.create_dataset('ereal', data=ereal) file_handle.create_dataset('efourier', data=efourier)
# create phaser phaser = _spimage.sp_phaser_alloc() _spimage.sp_phaser_init(phaser, phase_alg, sup_alg, _spimage.SpEngineCUDA) _spimage.sp_phaser_set_amplitudes(phaser, amplitudes) _spimage.sp_phaser_init_model(phaser, real_space, 0) _spimage.sp_phaser_init_support(phaser, support, 0, 0) #real_space_s = _spimage.sp_image_shift(real_space) fourier_space = _spimage.sp_image_ifftw3(real_space) ereal_start = _numpy.sqrt((abs(real_space.image[~_numpy.bool8(support.image)])**2).sum() / (abs(real_space.image)**2).sum()) efourier_start = _numpy.sqrt(((abs(fourier_space.image[_numpy.bool8(amplitudes.mask)]) - abs(amplitudes.image[_numpy.bool8(amplitudes.mask)]))**2).sum() / ((abs(amplitudes.image[_numpy.bool8(amplitudes.mask)])**2).sum() + (abs(fourier_space.image[~_numpy.bool8(amplitudes.mask)])**2).sum())) _spimage.sp_phaser_iterate(phaser, options.number_of_iterations) model_out = _spimage.sp_phaser_model(phaser) support_out = _spimage.sp_phaser_support(phaser) fmodel_out = _spimage.sp_phaser_fmodel(phaser) real_space_end = _spimage.sp_phaser_model_before_projection(phaser) fourier_space_end = _spimage.sp_phaser_fmodel(phaser) ereal_end = _numpy.sqrt((abs(real_space_end.image[~_numpy.bool8(support.image)])**2).sum() / (abs(real_space_end.image)**2).sum()) efourier_end = _numpy.sqrt(((abs(fourier_space_end.image[_numpy.bool8(amplitudes.mask)]) - abs(amplitudes.image[_numpy.bool8(amplitudes.mask)]))**2).sum() / ((abs(amplitudes.image[_numpy.bool8(amplitudes.mask)])**2).sum() + (abs(fourier_space_end.image[~_numpy.bool8(amplitudes.mask)])**2).sum())) _spimage.sp_image_write(model_out, "%s/real_space-%s.h5" % (options.output_dir, options.output_affix), 0) _spimage.sp_image_write(support_out, "%s/support-%s.h5" % (options.output_dir, options.output_affix), 0) _spimage.sp_image_write(fmodel_out, "%s/fourier_space-%s.h5" % (options.output_dir, options.output_affix), 0) print "Ereal: %g -> %g" % (ereal_start, ereal_end) print "Efourier: %g -> %g" % (efourier_start, efourier_end)
np3 = np1[np.newaxis, np.newaxis, :] + a number_of_scattered_photons = 10**int( np3.flatten()[index]) * (particle_size / 20)**2 #10 is smallest radius array_size = particle_size + 5 #Generate diffraction pattern particle = ElserParticle(array_size, particle_size, feature_size) detected_intensity, diffracted_wave, support = particle.generate_pattern( pattern_size_pixels, detector_distance, detector_pixel_size, wavelength, number_of_scattered_photons) #Write to file img_detected_intensity = spimage_tools.image_from_array(detected_intensity) img_diffracted_wave = spimage_tools.image_from_array(diffracted_wave) img_support = spimage_tools.image_from_array(support) version = 'testrun' output_dir = '/scratch/fhgfs/elsin/' + version + '/particles/' shell_functions.mkdir_p(output_dir) filename1 = output_dir + '/p{0:06d}'.format(index) + '_detected_intensity.h5' filename2 = output_dir + '/p{0:06d}'.format(index) + '_diffracted_wave.h5' filename3 = output_dir + '/p{0:06d}'.format(index) + '_support.h5' spimage.sp_image_write(img_detected_intensity, filename1, 0) spimage.sp_image_write(img_diffracted_wave, filename2, 0) spimage.sp_image_write(img_support, filename3, 0) image = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(diffracted_wave))) plt.imsave(output_dir + '/p{0:06d}'.format(index) + 'img.png', abs(image))
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)
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)
def run_it(number_of_iterations): spimage.sp_phaser_iterate(phaser, number_of_iterations) run_it(NUMBER_OF_ITERATIONS) phaser.algorithm = phase_alg_refine run_it(NUMBER_OF_REFINE_ITERATIONS) #Output data model = spimage.sp_phaser_model(phaser) support = spimage.sp_phaser_support(phaser) fmodel = spimage.sp_phaser_fmodel(phaser) spimage.sp_image_write( model, OUTPUT_DIR + "index{0:06d}".format(index) + "run{0:06d}model.h5".format(run), 0) spimage.sp_image_write( support, OUTPUT_DIR + "index{0:06d}".format(index) + "run{0:06d}support.h5".format(run), 0) spimage.sp_image_write( fmodel, OUTPUT_DIR + "index{0:06d}".format(index) + "run{0:06d}fmodel.h5".format(run), 0) ereal = spimage.sp_phaser_ereal(phaser) efourier = spimage.sp_phaser_efourier(phaser) filename = OUTPUT_DIR + 'index{0:06d}'.format( index) + 'run{0:06d}error.h5'.format(run) with h5py.File(filename, 'w') as file_handle:
img_real_space = spimage_tools.image_from_array(real_space) img_real_space.phased = 0 img_real_space.shifted = 0 img_real_space.detector.detector_distance = settings['detector_distance'] img_real_space.detector.pixel_size[:] = settings['detector_pixel_size'] img_real_space.detector.wavelength = settings['wavelength'] output_dir = output_dir + 'particle_' + particle_id shell_functions.mkdir_p(output_dir) file1 = output_dir + '/particle_detected_intensity.h5' file2 = output_dir + '/particle_diffracted_wave.h5' file3 = output_dir + '/particle_support.h5' file4 = output_dir + '/particle_shape.hdf5' file5 = output_dir + '/particle_real_space.h5' spimage.sp_image_write(img_detected_intensity, file1, 0) spimage.sp_image_write(img_diffracted_wave, file2, 0) spimage.sp_image_write(img_support, file3, 0) spimage.sp_image_write(img_real_space, file5, 0) with h5py.File(file4, "w") as f: dset = f.create_dataset("particle_matrix", data=particle.particle) dset.attrs['particle_size'] = particle_size dset.attrs['feature_size'] = feature_size dset.attrs['n_photons'] = settings['number_of_photons'] image = np.fft.fftshift(np.fft.fft2(np.fft.fftshift(diffracted_wave))) plt.imsave(output_dir + '/particle_projection_img.png', abs(image))
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)
def image_to_png(arguments): if isinstance(arguments,str): arguments = [arguments] elif not isinstance(arguments,list): print "function to_png takes must have a list or string input" return if len(sys.argv) <= 1: print """ Usage: python_script_image_to_png <image_in.h5> <image_out.h5> [colorscale] Colorscales: Jet Gray PosNeg InvertedPosNeg Phase InvertedPhase Log (can be combined with the others) Shift (can be combined with the others) """ exit(1) try: img = spimage.sp_image_read(arguments[0],0) except: print "Error: %s is not a readable .h5 file\n" % arguments[0] exit(1) log_flag = 0 shift_flag = 0 for flag in arguments[2:]: 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 else: print "unknown flag %s" % flag if log_flag == 1: color += 128 if shift_flag == 1: img = spimage.sp_image_shift(img) try: spimage.sp_image_write(img,arguments[1],color) except: print "Error: Can not write %s\n" % arguments[1] exit(1)
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)
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)
def put_neg_to_zero(image_file_name, output_file_name): img = spimage.sp_image_read(image_file_name, 0) new_img = img.image new_img[real(img.image) < 0.] = 0. img.image[:, :] = new_img spimage.sp_image_write(img, output_file_name, 0)
mask = _numpy.bool8(amplitudes.mask) efourier_start = _numpy.sqrt( ((abs(fourier_space.image[mask]) - abs(amplitudes.image[mask]))** 2).sum() / ((abs(amplitudes.image[mask])**2).sum() + (abs(fourier_space.image[~mask])**2).sum())) _spimage.sp_phaser_iterate(phaser, args.number_of_iterations) model_out = _spimage.sp_phaser_model(phaser) support_out = _spimage.sp_phaser_support(phaser) fmodel_out = _spimage.sp_phaser_fmodel(phaser) real_space_end = _spimage.sp_phaser_model_before_projection(phaser) fourier_space_end = _spimage.sp_phaser_fmodel(phaser) ereal_end = _numpy.sqrt((abs(real_space_end.image[~support])**2).sum() / (abs(real_space_end.image)**2).sum()) efourier_end = _numpy.sqrt( ((abs(fourier_space_end.image[mask]) - abs(amplitudes.image[mask]))** 2).sum() / ((abs(amplitudes.image[mask])**2).sum() + (abs(fourier_space_end.image[~mask])**2).sum())) _spimage.sp_image_write(model_out, f"{args.outdir}/real_space-{args.affix}.h5", 0) _spimage.sp_image_write(support_out, f"{args.outdir}/support-{args.affix}.h5", 0) _spimage.sp_image_write(fmodel_out, f"{args.outdir}/fourier_space-{args.affix}.h5", 0) print("Ereal: %g -> %g" % (ereal_start, ereal_end)) print("Efourier: %g -> %g" % (efourier_start, efourier_end))