def show_support_fmodel_model_slice_2D(run_dir, iteration=None, save_imgs=False, output_folder='pngs'): if iteration == None: iteration = return_last_iteration_integer(run_dir + '/output_mnt/') print os.getcwd(), iteration model = spimage.sp_image_shift( spimage.sp_image_read( '{r}/output_mnt/model_{i}.h5'.format(r=run_dir, i=iteration), 0)) fmodel = spimage.sp_image_shift( spimage.sp_image_read( '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=iteration), 0)) support = spimage.sp_image_shift( spimage.sp_image_read( '{r}/output_mnt/support_{i}.h5'.format(r=run_dir, i=iteration), 0)) s = np.shape(model.image)[0] / 2 matplotlib.rcParams.update({'font.size': 16}) f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(30, 10)) ax1.set_title('Model') ax1.imshow(np.absolute(model.image)) ax2.set_title('Fourier amplitude') ax2.imshow(log10(np.absolute(fmodel.image))) ax3.set_title('Support') ax3.imshow(np.absolute(support.image)) plt.tight_layout() if save_imgs: plt.savefig(os.path.join(output_folder, run_dir + '.png')) plt.close(f)
def save_absolute_phase_real_fourier(run_dir, output_folder, i=None, shift=True, save_img=True): if i == None: i = return_last_iteration_integer(os.path.join(run_dir, 'output_mnt')) model = spimage.sp_image_read( '{r}/output_mnt/model_{i}.h5'.format(r=run_dir, i=i), 0) fmodel = spimage.sp_image_read( '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=i), 0) if model == None or fmodel == None: print run_dir + ' failed' return if shift: model = spimage.sp_image_shift(model) fmodel = spimage.sp_image_shift(fmodel) s = np.shape(model.image)[0] / 2 #matplotlib.rcParams.update({'font.size': 16}) f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 15)) ax1.set_title('Absolute') ax1.imshow(np.absolute(model.image[s, :, :])) ax2.set_title('Phase') ax2.imshow(np.angle(model.image[s, :, :]), cmap='PiYG') ax3.set_title('Real part') ax3.imshow(np.real(model.image[s, :, :]), cmap='coolwarm') ax4.set_title('Fourier') ax4.imshow(np.absolute(fmodel.image[s, :, :]), norm=LogNorm()) f.subplots_adjust(wspace=1, hspace=1) plt.tight_layout() if save_img: plt.savefig(os.path.join(output_folder, run_dir + '.png')) spimage.sp_image_free(model) spimage.sp_image_free(fmodel) plt.close(f)
def show_2Dhawk_result_real_fourier(iteration): re = spimage.sp_image_shift( spimage.sp_image_read('real_space-{0:07}.h5'.format(iteration), 0)) fo = spimage.sp_image_shift( spimage.sp_image_read('fourier_space-{0:07}.h5'.format(iteration), 0)) f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 8)) ax1.imshow(np.absolute(re.image)) ax2.imshow(log10(absolute(fo.image))) plt.tight_layout() plt.savefig('real_and_fourier_{i}.png'.format(i=str(iteration)))
def plot_prtf_results_3D(d, input_image, downsampling, save_file=True, image_name='PRTF_results.png', zoom=True): f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(20, 13)) ax1.set_title('Average Real space') avg_img = spimage.sp_image_shift( spimage.sp_image_read(os.path.join(d, 'PRTF-avg_image.h5'), 0)) avg_f = spimage.sp_image_shift( spimage.sp_image_read(os.path.join(d, 'PRTF-avg_fft.h5'), 0)) input_img = spimage.sp_image_read(input_image, 0) size = np.shape(input_img.image)[0] sl = (size / 2, slice(None), slice(None)) if zoom: z = int( (size - np.count_nonzero(avg_img.image[size / 2, size / 2, :])) / 2.2) sl_real = (size / 2, slice(z, size - z), slice(z, size - z)) elif zoom == False: sl_real = sl print sl_real ax1.imshow(np.absolute(avg_img.image)[sl_real]) ax2.set_title('Input pattern') ax2.imshow(np.absolute(input_img.image * input_img.mask)[sl], norm=LogNorm()) ax3.set_title('PRTF') prtf_radavg, q = prtf_radial_average(d, downsampling) ax3.plot(q, prtf_radavg, lw=1.5) ax3.set_xlabel(r'$|q|[nm^{-1}]$', fontsize=18) ax3.set_ylabel(r'$PRTF$', fontsize=18) ax3.axhline(1 / math.e, c='k') ax4.set_title('Phase') ax4.imshow(np.angle(avg_img.image)[sl_real], cmap='PiYG') ax5.set_title('Average Fourier Space') ax5.imshow(np.absolute(avg_f.image)[sl]) ax6.set_title('Errors') errors = extract_final_errors(os.getcwd()) errors.sort(order='fourier_error') ax6.plot(range(len(errors['fourier_error'])), errors['fourier_error'], lw=1.5, label='Fourier Error') errors.sort(order='real_error') ax6.plot(range(len(errors['real_error'])), errors['real_error'], lw=1.5, label='Real Error') plt.legend() plt.tight_layout() if save_file: plt.savefig(image_name)
def plot_prtf_results_2D(d, input_image, shift_input=False, save_file=True, image_name='PRTF_results.png'): f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2, 3, figsize=(30, 20)) ax1.set_title('Average Real space') avg_img = spimage.sp_image_shift( spimage.sp_image_read(os.path.join(d, 'PRTF-avg_image.h5'), 0)) avg_f = spimage.sp_image_shift( spimage.sp_image_read(os.path.join(d, 'PRTF-avg_fft.h5'), 0)) if shift_input: input_img = spimage.sp_image_shift( spimage.sp_image_read(input_image, 0)) else: input_img = spimage.sp_image_read(input_image, 0) ax1.imshow(np.absolute(avg_img.image)) ax2.set_title('Input pattern') ax2.imshow(np.absolute(input_img.image * input_img.mask), norm=LogNorm()) ax3.set_title('PRTF') prtf_radavg, q = prtf_radial_average(d, downsampling) ax3.plot(pix_to_q(p[:, 0], 1.035e-9, 0.7317, 0.0006), p[:, 1], lw=1.5) ax3.set_xlabel(r'$|q|[nm^{-1}]$', fontsize=18) ax3.set_ylabel(r'$PRTF$', fontsize=18) ax3.axhline(1 / math.e, c='k') ax4.set_title('Phase') ax4.imshow(np.angle(avg_img.image), cmap='PiYG') ax5.set_title('Average Fourier Space') ax5.imshow(np.absolute(avg_f.image)) ax6.set_title('Errors') errors = extract_final_errors(os.getcwd()) errors.sort(order='fourier_error') ax6.plot(range(len(errors['fourier_error'])), errors['fourier_error'], lw=1.5, c='r', label='Fourier Error') errors.sort(order='real_error') ax6.plot(range(len(errors['real_error'])), errors['real_error'], lw=1.5, c='g', label='Real Error') plt.legend() plt.tight_layout() if save_file: plt.savefig(image_name)
def show_img_times_mask(input_file, s='x', save_file=True, output_file_name=None): im = spimage.sp_image_read(input_file, 0) if len(shape(im.image)) == 2: fig = plt.figure('image and mask', figsize=(10, 10)) fig.clear() plt.imshow(np.absolute(im.image) * im.mask, norm=LogNorm()) plt.colorbar() if len(shape(im.image)) == 3: if s == 'x': sl = (np.shape(im.image)[0] / 2, slice(None), slice(None)) if s == 'y': sl = (slice(None), shape(im.image)[0] / 2, slice(None)) if s == 'z': sl = (slice(None), slice(None), shape(im.image)[0] / 2) fig = plt.figure('image and mask', figsize=(10, 10)) fig.clear() fig.add_subplot(2, 1, 1) plt.imshow(np.absolute(im.image[0, :, :]) * im.mask[0, :, :], norm=LogNorm()) fig.add_subplot(2, 1, 2) plt.imshow(np.absolute(im.image[sl]) * im.mask[sl], norm=LogNorm()) if save_file: if output_file_name == None: plt.savefig(input_file.replace('h5', 'png')) else: plt.savefig(output_file_name)
def show_center_speckle_mask(input_file, radius_array, prefix='center_speckle_mask', save_img=False): img = spimage.sp_image_read(input_file, 0) n = len(radius_array) c = np.shape(img.image)[0] / 2 img_dim = np.max(radius_array) * 1.5 fig, ax = plt.subplots(figsize=(9, 3 * n), nrows=n, ncols=3) for i, r in enumerate(radius_array): print i, r ax[i][0].set_title('Mask radius = ' + str(r)) mask = ida_phasing.mask_center(input_file, r, save_file=False) ax[i][0].imshow( np.absolute(img.image[c, c - img_dim:c + img_dim, c - img_dim:c + img_dim]) * mask.mask[c, c - img_dim:c + img_dim, c - img_dim:c + img_dim], interpolation='nearest') ax[i][1].imshow( np.absolute(img.image[c - img_dim:c + img_dim, c, c - img_dim:c + img_dim]) * mask.mask[c - img_dim:c + img_dim, c, c - img_dim:c + img_dim], interpolation='nearest') ax[i][2].imshow( np.absolute(img.image[c - img_dim:c + img_dim, c - img_dim:c + img_dim, c]) * mask.mask[c - img_dim:c + img_dim, c - img_dim:c + img_dim, c], interpolation='nearest') plt.tight_layout() if save_img: plt.savefig(prefix)
def plot_real_space(n, png_output='real_space_pngs', iteration='4009'): for j in range(n): fig, axes = plt.subplots(figsize=(9, 3), nrows=1, ncols=3) real_space = np.real( spimage.sp_image_shift( spimage.sp_image_read( 'run_%04d/output_mnt/model_%s.h5' % (j, iteration), 0)).image) dim = np.shape(real_space)[0] nonzero = np.shape(real_space[real_space > 0.])[0] new_dim = (dim / 2 - nonzero**(1 / 3)) / 2 vmax = real_space.max() vmin = real_space.min() axes[0].imshow(real_space[dim / 2, new_dim:-new_dim, new_dim:-new_dim], vmax=vmax, vmin=vmin) axes[1].imshow(real_space[new_dim:-new_dim, dim / 2, new_dim:-new_dim], vmax=vmax, vmin=vmin) im = axes[2].imshow(real_space[new_dim:-new_dim, new_dim:-new_dim, dim / 2], vmax=vmax, vmin=vmin) fig.colorbar(im, ax=axes.ravel().tolist()) print png_output + '/%04d.png' % j plt.savefig(png_output + '/%04d.png' % j) plt.close(fig)
def plot_phases(in_file, plot_type, plot_log): flags = ['histogram','phases'] plot_flag = 0 log_flag = 0 def no_log(x): return x fig = pylab.figure(1) ax = fig.add_subplot(111) try: img = spimage.sp_image_read(in_file,0) except: raise IOError("Can't read %s." % in_file) values = img.image.reshape(pylab.size(img.image)) if plot_log: log_function = pylab.log else: log_function = no_log if plot_type == PHASES: hist = pylab.histogram(pylab.angle(values),bins=500) ax.plot((hist[1][:-1]+hist[1][1:])/2.0,log_function(hist[0])) elif plot_flag == HISTOGRAM: hist = pylab.histogram2d(pylab.real(values),pylab.imag(values),bins=500) ax.imshow(log_function(hist[0]),extent=(hist[2][0],hist[2][-1],-hist[1][-1],-hist[1][0]),interpolation='nearest') else: ax.plot(pylab.real(values),pylab.imag(values),'.') return fig
def image_info(filename): try: img = spimage.sp_image_read(filename, 0) except IOError: print("Error: Can not read image %s" % filename) exit(1) print(f"{filename}: ({img.num_dimensions}D image)") if img.num_dimensions == 3: print("size = %d x %d x %d" % (spimage.sp_image_x(img), spimage.sp_image_y(img), spimage.sp_image_z(img))) print("center = %g x %g x %g" % (img.detector.image_center[0], img.detector.image_center[1], img.detector.image_center[2])) else: print("size = %d x %d" % (spimage.sp_image_x(img), spimage.sp_image_y(img))) print("center = %g x %g" % (img.detector.image_center[0], img.detector.image_center[1])) print("shifted = %d" % img.shifted) print("scaled = %d" % img.scaled) print("phased = %d" % img.phased) print("wavelength = %g" % img.detector.wavelength) print("detector distance = %g" % img.detector.detector_distance) if img.num_dimensions == 3: print("pixel size = %g x %g x %g" % (img.detector.pixel_size[0], img.detector.pixel_size[1], img.detector.pixel_size[2])) else: print("pixel size = %g x %g" % (img.detector.pixel_size[0], img.detector.pixel_size[1]))
def image_histogram(file_name, shift=False, mode='absolute', only_nonzero=True, cf=0., radius_cutoff=None, b=100): if mode == 'absolute': f = np.absolute elif mode == 'angle': f = np.angle elif mode == 'real': f = np.real elif mode == 'imag': f = np.imag print type(file_name) if type(file_name) == str: img = spimage.sp_image_read(file_name, 0) elif type(file_name) != str: img = file_name if shift: print 'shifting image' img = spimage.sp_image_shift(img) if radius_cutoff != None: r = stuff.r_array_3D(np.shape(img.image)[0]) new_img = img.image[np.where(r < radius_cutoff)] flat_img = f(new_img).flatten() else: flat_img = f(img.image[:]).flatten() print flat_img if only_nonzero: flat_img = flat_img[flat_img != 0.] if cf != 0.: flat_img = flat_img[flat_img > cf] plt.hist(flat_img, bins=b) return flat_img
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 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 create_main_frame(self, filename): self.main_frame = QWidget() self.image = None try: self.img = spimage.sp_image_read(filename,0) except: print "Must provide a file" exit(1) self.image = self.img.image x_array = arange(shape(self.image)[0]) - self.img.detector.image_center[0] y_array = arange(shape(self.image)[1]) - self.img.detector.image_center[1] X_array, Y_array = meshgrid(x_array, y_array) X_array = transpose(X_array); Y_array = transpose(Y_array) self.r = sqrt(X_array**2 + Y_array**2) self.auto_unfiltered = fftshift(abs(fft2(self.image))) self.dpi = 100 self.fig = Figure((10.0, 10.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.axes = self.fig.add_subplot(111) self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) self.a_slider = QSlider(Qt.Vertical) self.a_slider.setMinimum(1) self.a_slider.setMaximum(300) self.a_slider.setValue(self.a) self.a_slider.setTracking(False) self.a_label = QLabel("a = %g" % self.a) self.connect(self.a_slider, SIGNAL('sliderMoved(int)'), self.a_changed) self.connect(self.a_slider, SIGNAL('valueChanged(int)'), self.update_image) #self.filter_label = QLabel("Use filter") self.filter_box = QCheckBox("Use filter") self.connect(self.filter_box, SIGNAL('stateChanged(int)'), self.box_state_changed) vbox1 = QVBoxLayout() vbox1.addWidget(self.canvas) vbox1.addWidget(self.mpl_toolbar) vbox2 = QVBoxLayout() vbox2.addWidget(self.a_label) vbox2.addWidget(self.a_slider) vbox2.addWidget(self.filter_box) hbox = QHBoxLayout() hbox.addLayout(vbox1) hbox.addLayout(vbox2) self.main_frame.setLayout(hbox) self.setCentralWidget(self.main_frame) self.update_image()
def plot_phases(in_file, plot_type, plot_log): plot_flag = 0 def no_log(x): return x fig = pylab.figure(1) ax = fig.add_subplot(111) try: img = spimage.sp_image_read(in_file, 0) except IOError: raise IOError("Can't read %s." % in_file) values = img.image.reshape(pylab.size(img.image)) if plot_log: log_function = pylab.log else: log_function = no_log if plot_type == PHASES: hist = pylab.histogram(pylab.angle(values), bins=500) ax.plot((hist[1][:-1] + hist[1][1:]) / 2, log_function(hist[0])) elif plot_flag == HISTOGRAM: hist = pylab.histogram2d(pylab.real(values), pylab.imag(values), bins=500) ax.imshow(log_function(hist[0]), extent=(hist[2][0], hist[2][-1], -hist[1][-1], -hist[1][0]), interpolation='nearest') else: ax.plot(pylab.real(values), pylab.imag(values), '.') return fig
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 image_info(filename): try: img = spimage.sp_image_read(filename,0) except: print "Error: Can not read image %s" % filename exit(1) print "%s: (%dD image)" % (filename,img.num_dimensions) if img.num_dimensions == 3: print "size = %d x %d x %d" % (spimage.sp_image_x(img), spimage.sp_image_y(img), spimage.sp_image_z(img)) print "center = %g x %g x %g" % (img.detector.image_center[0], img.detector.image_center[1], img.detector.image_center[2]) else: print "size = %d x %d" % (spimage.sp_image_x(img), spimage.sp_image_y(img)) print "center = %g x %g" % (img.detector.image_center[0], img.detector.image_center[1]) print "shifted = %d" % img.shifted print "scaled = %d" % img.scaled print "phased = %d" % img.phased print "wavelength = %g" % img.detector.wavelength print "detector distance = %g" % img.detector.detector_distance if img.num_dimensions == 3: print "pixel size = %g x %g x %g" % (img.detector.pixel_size[0], img.detector.pixel_size[1], img.detector.pixel_size[2]) else: print "pixel size = %g x %g" % (img.detector.pixel_size[0], img.detector.pixel_size[1])
def create_main_frame(self, filename): self.main_frame = QWidget() self.image = None try: self.img = spimage.sp_image_read(filename,0) except: print "Must provide a file" exit(1) self.image = self.img.image x_array = arange(shape(self.image)[0]) - self.img.detector.image_center[0] y_array = arange(shape(self.image)[1]) - self.img.detector.image_center[1] X_array, Y_array = meshgrid(x_array, y_array) self.r = sqrt(X_array**2 + Y_array**2) self.auto_unfiltered = fftshift(abs(fft2(self.image))) self.dpi = 100 self.fig = Figure((10.0, 10.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.axes = self.fig.add_subplot(111) self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) self.a_slider = QSlider(Qt.Vertical) self.a_slider.setMinimum(1) self.a_slider.setMaximum(300) self.a_slider.setValue(self.a) self.a_slider.setTracking(False) self.a_label = QLabel("a = %g" % self.a) self.connect(self.a_slider, SIGNAL('sliderMoved(int)'), self.a_changed) self.connect(self.a_slider, SIGNAL('valueChanged(int)'), self.update_image) #self.filter_label = QLabel("Use filter") self.filter_box = QCheckBox("Use filter") self.connect(self.filter_box, SIGNAL('stateChanged(int)'), self.box_state_changed) vbox1 = QVBoxLayout() vbox1.addWidget(self.canvas) vbox1.addWidget(self.mpl_toolbar) vbox2 = QVBoxLayout() vbox2.addWidget(self.a_label) vbox2.addWidget(self.a_slider) vbox2.addWidget(self.filter_box) hbox = QHBoxLayout() hbox.addLayout(vbox1) hbox.addLayout(vbox2) self.main_frame.setLayout(hbox) self.setCentralWidget(self.main_frame) self.update_image()
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 show_slice(input_file, shift=True): im = spimage.sp_image_read(input_file, 0) if shift: im = spimage.sp_image_shift(im) s = np.shape(im.image)[0] / 2 fig = plt.figure(1, figsize=(10, 10)) fig.clear() plt.imshow(np.absolute(im.image)[s, :, :])
def radial_sort(img_file, shift=True): img_array = np.absolute(spimage.sp_image_read(img_file, 0).image) if shift: img_array = np.fft.fftshift(img_array) #r=stuff.r_array_3D(np.shape(img_array)[0], ndimage.measurements.center_of_mass(img_array)) r = stuff.r_array_3D(np.shape(img_array)[0]) r_flat = r.flatten() img_flat = img_array.flatten() sort_order = np.argsort(r_flat) return r_flat[sort_order], img_flat[sort_order]
def show_support_fmodel_model_slice(run_dir, iteration=None, save_imgs=False, output_folder='pngs', s='x'): if iteration == None: iteration = ida_phasing.return_last_iteration_integer(run_dir + '/output_mnt/') print os.getcwd(), iteration model = spimage.sp_image_shift( spimage.sp_image_read( '{r}/output_mnt/model_{i}.h5'.format(r=run_dir, i=iteration), 0)) fmodel = spimage.sp_image_shift( spimage.sp_image_read( '{r}/output_mnt/fmodel_{i}.h5'.format(r=run_dir, i=iteration), 0)) support = spimage.sp_image_shift( spimage.sp_image_read( '{r}/output_mnt/support_{i}.h5'.format(r=run_dir, i=iteration), 0)) sh = np.shape(model.image)[0] / 2 #matplotlib.rcParams.update({'font.size': 16}) f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 15)) print s if s == 'x': sl = (sh, slice(None), slice(None)) print 'x' if s == 'y': sl = (slice(None), sh, slice(None)) print 'y' if s == 'z': sl = (slice(None), slice(None), sh) print 'z' ax1.set_title('Model') ax1.imshow(np.absolute(model.image[sl])) ax2.set_title('Fourier amplitude') ax2.imshow(log10(np.absolute(fmodel.image[sl]))) ax3.set_title('Support') ax3.imshow(np.absolute(support.image[sl])) ax4.set_title('Phase') ax4.imshow(np.angle(model.image[sl])) if save_imgs: plt.savefig(os.path.join(output_folder, run_dir + '.png')) plt.close(f)
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 plot_img_with_circle(image_file_name, r=20.): #Shows an image with a circle of given radius around the image center img = spimage.sp_image_read(image_file_name, 0) print np.shape(img.image) circle1 = plt.Circle(img.detector.image_center, r, color='r', fill=False) fig = plt.gcf() negatives = np.real(img.image) print shape(negatives) negatives[np.real(img.image) > 0.] = 0. plt.imshow(np.absolute(img.image)) fig.gca().add_artist(circle1)
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 convert_to_png(output_folder='pngs'): try: os.mkdir(output_folder) except OSError: None imgs = [i for i in os.listdir('.') if i.endswith('.h5')] for im in imgs: img = spimage.sp_image_read(im, 0) fig = pylab.figure(1) pylab.imshow(absolute(numpy.log10(img.image)) * img.mask) pylab.savefig(os.path.join(output_folder, im.replace('.h5', '.png'))) fig.clf()
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 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 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 _create_main_frame(self, filename): self._main_frame = QtGui.QWidget() self._image = None try: self._image_sp = spimage.sp_image_read(filename,0) except: print "Must provide a file" exit(1) self._image = self._image_sp.image self._dpi = 100 self._fig = Figure((10.0, 10.0), dpi=self._dpi) self._fig.subplots_adjust(left=0., right=1., bottom=0., top=1.) self._canvas = FigureCanvas(self._fig) self._canvas.setParent(self._main_frame) self._axes = self._fig.add_subplot(111) self._axes.set_xticks([]) self._axes.set_yticks([]) self._mpl_toolbar = NavigationToolbar(self._canvas, self._main_frame) self._slider_length = 100 self._angle_slider = QtGui.QSlider(QtCore.Qt.Vertical) self._angle_slider.setMinimum(0) self._angle_slider.setMaximum(self._slider_length) self._angle_slider.setValue(self._angle) self._angle_slider.setTracking(True) self._angle_label = QtGui.QLabel("angle = %g" % (self._angle/pi*180.)) self._angle_label.setFixedWidth(100) #self.connect(self._angle_slider, SIGNAL('sliderMoved(int)'), self._angle_changed) self._angle_slider.sliderMoved.connect(self._angle_changed) vbox1 = QtGui.QVBoxLayout() vbox1.addWidget(self._canvas) vbox1.addWidget(self._mpl_toolbar) vbox2 = QtGui.QVBoxLayout() vbox2.addWidget(self._angle_label) vbox2.addWidget(self._angle_slider) hbox = QtGui.QHBoxLayout() hbox.addLayout(vbox1) hbox.addLayout(vbox2) self._main_frame.setLayout(hbox) self.setCentralWidget(self._main_frame) self._update_image()
def radial_average_q(file_name, downsampling): img = spimage.sp_image_read(file_name, 0) s = np.shape(img.image) r, radavg = spimage.radialMeanImage(img.image, cx=0., cy=0., cz=0., output_r=True) q = pix_to_q(r, 1.035e-9, 0.7317, 0.000075 * downsampling) q /= 1e09 #reciprocal nanometres q_edge = pix_to_q(s[0] / 2, 1.035e-9, 0.7317, 0.000075 * downsampling) / 1e09 q_short = q[q <= q_edge] #Truncate prtf at detector edge return radavg[:len(q_short)], q_short
def prtf_radial_average(prtf_dir, downsampling): prtf = spimage.sp_image_read(os.path.join(prtf_dir, 'PRTF-prtf.h5'), 0) s = np.shape(prtf.image) r, prtf_radavg = spimage.radialMeanImage(prtf.image, cx=0., cy=0., cz=0., output_r=True) q = pix_to_q(r, 1.035e-9, 0.7317, 0.000075 * downsampling) q /= 1e09 #reciprocal nanometres q_edge = pix_to_q(s[0] / 2, 1.035e-9, 0.7317, 0.000075 * downsampling) / 1e09 q_short = q[q <= q_edge] #Truncate prtf at detector edge return prtf_radavg[:len(q_short)], q_short
def show_support_fmodel_model_slice2(iteration, save_imgs=False, output_folder='pngs'): model = spimage.sp_image_shift( spimage.sp_image_read('model_{i}.h5'.format(i=iteration), 0)) fmodel = spimage.sp_image_shift( spimage.sp_image_read('fmodel_{i}.h5'.format(i=iteration), 0)) support = spimage.sp_image_shift( spimage.sp_image_read('support_{i}.h5'.format(i=iteration), 0)) s = np.shape(model.image)[0] / 2 #matplotlib.rcParams.update({'font.size': 16}) f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 15)) ax1.set_title('Model') ax1.imshow(np.absolute(model.image[s, :, :])) ax2.set_title('Fourier amplitude') ax2.imshow(log10(np.absolute(fmodel.image[s, :, :]))) ax3.set_title('Support') ax3.imshow(np.absolute(support.image[s, :, :])) ax4.set_title('Phase') ax4.imshow(np.angle(model.image[s, :, :])) if save_imgs: plt.savefig(os.path.join(output_folder, '{i}.png'.format(i=iteration))) plt.close(f)
def real_space_residual_prtf_avg_image(reference_file=None, support_file=None, prtf_dir=None, d='.', mode='absolute'): if mode == 'absolute': f = np.absolute elif mode == 'angle': f = np.angle elif mode == 'real': f = np.real elif mode == 'imag': f = np.imag iteration = return_last_iteration_integer( os.path.join(d, 'run_0000/output_mnt')) if prtf_dir != None: model = f( spimage.sp_image_read(os.path.join(prtf_dir, 'PRTF-avg_image.h5'), 0).image[:]) else: prtf_dirs = [ os.path.join(d, i) for i in os.listdir(d) if i.startswith('prtf_') ] print prtf_dirs[0] model = f( spimage.sp_image_read( os.path.join(prtf_dirs[0], 'PRTF-avg_image.h5'), 0).image[:]) if support_file != None: support = real(spimage.sp_image_read(support_file, 0).image[:]) else: support = real( spimage.sp_image_read( os.path.join(d, 'run_0000/output_mnt/support_%04d.h5' % iteration), 0).image[:]) if reference_file != None: reference = f(spimage.sp_image_read(reference_file, 0).image[:]) else: reference = support.copy() return stuff.real_space_residual(reference, model, support, normalize=True)
def plot_image(in_file,*arguments): try: img = spimage.sp_image_read(in_file,0) except: print "Error: %s is not a readable .h5 file\n" % in_file plot_flags = ['abs','mask','phase','real','imag'] shift_flags = ['shift'] log_flags = ['log'] plot_flag = 0 shift_flag = 0 log_flag = 0 for flag in arguments: flag = flag.lower() if flag in plot_flags: plot_flag = flag elif flag in shift_flags: shift_flag = flag elif flag in log_flags: log_flag = flag else: print "unknown flag %s" % flag if shift_flag: img = spimage.sp_image_shift(img) def no_log(x): return x if log_flag: log_function = pylab.log else: log_function = no_log if (plot_flag == "mask"): pylab.imshow(img.mask,origin='lower',interpolation="nearest") elif(plot_flag == "phase"): pylab.imshow(pylab.angle(img.image),cmap='hsv',origin='lower',interpolation="nearest") elif(plot_flag == "real"): pylab.imshow(log_function(pylab.real(img.image)),origin='lower',interpolation="nearest") elif(plot_flag == "imag"): pylab.imshow(log_function(pylab.imag(img.image)),origin='lower',interpolation="nearest") else: pylab.imshow(log_function(abs(img.image)),origin='lower',interpolation="nearest") pylab.show()
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 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 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 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 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"
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)
import spimage as _spimage from optparse import OptionParser if __name__ == "__main__": parser = OptionParser(usage="%name -n NUMBER_OF_ITERATIONS -f DIFFRACTION_PATTERN -r REAL_SPACE_MODEL -s SUPPORT [-o OUTPUT_DIR -a AFFIX]") parser.add_option("-n", action="store", type="int", default=100, dest="number_of_iterations", help="Number of iterations of ER") parser.add_option("-f", action="store", type="string", default=None, dest="pattern", help="Diffraction pattern") parser.add_option("-r", action="store", type="string", default=None, dest="real_space", help="Starting real-space model") parser.add_option("-s", action="store", type="string", default=None, dest="support", help="Support") parser.add_option("-o", action="store", type="string", default=".", dest="output_dir", help="Output directory") parser.add_option("-a", action="store", type="string", default="refined", dest="output_affix", help="This name will be added to all output files.") options, args = parser.parse_args() _numpy.random.seed() _spimage.sp_srand(_numpy.random.randint(1e6)) intensities = _spimage.sp_image_read(options.pattern, 0) if intensities.shifted == 0: amplitudes = _spimage.sp_image_shift(intensities) else: amplitudes = _spimage.sp_image_duplicate(intensities, _spimage.SP_COPY_ALL) _spimage.sp_image_dephase(amplitudes) _spimage.sp_image_to_amplitudes(amplitudes) real_space = _spimage.sp_image_read(options.real_space, 0) support = _spimage.sp_image_read(options.support, 0) phase_alg = _spimage.sp_phasing_er_alloc(_spimage.SpNoConstraints) sup_alg = _spimage.sp_support_array_init(_spimage.sp_support_static_alloc(), 20) # create phaser
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): 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)
import sys, pylab, spimage log_flags = ['log'] def plot_phases(in_file,*arguments): flags = ['histogram','phases'] plot_flag = 0 log_flag = 0 def no_log(x): return x fig = pylab.figure(1) ax = fig.add_subplot(111) n try: img = spimage.sp_image_read(in_file,0) except: print "Error when reading %s.\n" % in_file return values = img.image.reshape(pylab.size(img.image)) for flag in arguments: if flag in flags: plot_flag = flag elif flag in log_flags: log_flag = flag else: print "unknown flag %s" % flag if log_flag == 'log': log_function = pylab.log
#!/usr/bin/python import spimage import pylab # Read input image img = spimage.sp_image_read('../ring/raw_ring.h5',0) # Convolute with a 2 pixel # standard deviation gaussian img_blur = spimage.sp_gaussian_blur(img,2.0) rel_diff = abs((pylab.real(img_blur.image)- pylab.real(img.image)) /pylab.real(img_blur.image)) # Plot relative difference pylab.imshow(rel_diff,vmin = 0,vmax = 0.5) pylab.colorbar() pylab.show()
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)
matplotlib.use("WxAgg") matplotlib.interactive(True) from pylab import * import spimage import sys import numpy import time from enthought.mayavi import mlab img = None shift = False log = False plot_mask = False try: img = spimage.sp_image_read(sys.argv[1], 0) except: print "Must provide h5 image to read" # 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