我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.imsave()。
def resize_folder(folder, extensions = ['jpg','jpeg','png'], size = (100,100)): ''' Resizes all images in a specified folder to given size and overwrites all images in a folder Inputs: folder: string, full path to the folder with images extensions: list, list of valid extensions size: tuple, size of the output images ''' img_paths = get_images_from_directory(folder,extensions) resized_imgs = [imresize(plt.imread(im_pth)[:,:,:3],size) for im_pth in img_paths] for p,r_im in zip(img_paths,resized_imgs): plt.imsave(p,r_im)
def ColorRamp(output_format="png", colormap=GREY_HILLS): def _format(pixels, data_format): if data_format is not "raw": raise Exception("raw data is required") if pixels.data.dtype != np.uint8: raise Exception("data must be uint8") out = BytesIO() plt.imsave( out, pixels.data[0], cmap=colormap, vmin=0, vmax=255, format=output_format) return (CONTENT_TYPES[output_format], out.getvalue()) return _format
def create_image(g, path): path = os.path.relpath(path) if pygraphviz: a = nx.nx_agraph.to_agraph(g) # ['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop'] a.layout(prog='neato', args="-Goverlap=false -Gsplines=true") # splines=true a.draw(path) elif plt: nodes = g.nodes(True) colors = [attrs['color'] for n, attrs in nodes] labels = {n: attrs['label'] for n, attrs in nodes} if graphviz_layout: pos = graphviz_layout(g) else: pos = nx.spring_layout(g) nx.draw_networkx_nodes(g, pos, node_shape='o', node_color=colors, alpha=0.3) nx.draw_networkx_edges(g, pos, style='solid', alpha=0.2) nx.draw_networkx_labels(g, pos, labels, alpha=0.5) # plt.show() plt.imsave(path) # todo: this is not tested! print 'Image saved to', path
def process(input_dir, output_dir, model_dir, resizing_size, gpu): gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3, visible_device_list=gpu) with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)).as_default(): m = loader.LoadedModel(model_dir) os.makedirs(output_dir, exist_ok=True) input_filenames = glob(os.path.join(input_dir, '*.jpg')) + \ glob(os.path.join(input_dir, '*.png')) + \ glob(os.path.join(input_dir, '*.tif')) + \ glob(os.path.join(input_dir, '*.jp2')) for path in tqdm(input_filenames): img = Image.open(path).resize(resizing_size) mat = np.asarray(img) if len(mat.shape) == 2: mat = np.stack([mat, mat, mat], axis=2) predictions = m.predict(mat[None], prediction_key='labels')[0] plt.imsave(os.path.join(output_dir, os.path.relpath(path, input_dir)), predictions)
def do_batches(self, fn, batch_generator, metrics): loss_total = 0 batch_count = 0 for i, batch in enumerate(tqdm(batch_generator)): inputs, targets, weights, _ = batch err, l2_loss, acc, dice, true, prob, prob_b = fn(inputs, targets, weights) metrics.append([err, l2_loss, acc, dice]) metrics.append_prediction(true, prob_b) if i % 10 == 0: im = np.hstack(( true[:OUTPUT_SIZE**2].reshape(OUTPUT_SIZE,OUTPUT_SIZE), prob[:OUTPUT_SIZE**2][:,1].reshape(OUTPUT_SIZE,OUTPUT_SIZE))) plt.imsave(os.path.join(self.image_folder,'{0}_epoch{1}.png'.format(metrics.name, self.epoch)),im) loss_total += err batch_count += 1 return loss_total / batch_count
def log_images(self, tag, images, step): """Logs a list of images.""" im_summaries = [] for nr, img in enumerate(images): # Write the image to a string s = StringIO() plt.imsave(s, img, format='png') # Create an Image object img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1]) # Create a Summary value im_summaries.append(tf.Summary.Value(tag='%s/%d' % (tag, nr), image=img_sum)) # Create and write Summary summary = tf.Summary(value=im_summaries) self.writer.add_summary(summary, step)
def update_fig(*args): global total_it for it_i in range(iterations_per_paint): idxs = np.random.permutation(size) n_batches = len(idxs) // batch_size for batch_i in range(n_batches): idxs_i = idxs[batch_i * batch_size : (batch_i + 1) * batch_size] sess.run(optimizer, feed_dict={X: train_X[idxs_i], Y: train_Y[idxs_i]}) training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y}) print(total_it, training_cost) total_it += 1 outimg = pred_Y.eval(feed_dict={X: train_X}, session=sess) outimg = np.clip(outimg.reshape(img.shape), 0, 255).astype(np.uint8) img_plot.set_data(outimg) output_file_it = "%s/%07d.jpg" % (output_folder, total_it) # Saves the predicted image. #plt.imsave(output_file_it, outimg) # Saves the entire figure. plt.savefig(output_file_it, format="jpg") return img_plot,
def analyze(context, perf): fig = plt.figure(figsize=(14,13)) ax1 = fig.add_subplot(211) perf.portfolio_value.plot(ax=ax1, grid=True) ax1.set_ylabel('portfolio value in $') ax2 = fig.add_subplot(212) perf['GOOG'].plot(ax=ax2) perf[['short_mavg', 'long_mavg']].plot(ax=ax2) perf_trans = perf.ix[[t != [] for t in perf.transactions]] buys = perf_trans.ix[[t[0]['amount'] > 0 for t in perf_trans.transactions]] sells = perf_trans.ix[ [t[0]['amount'] < 0 for t in perf_trans.transactions]] ax2.plot(buys.index, perf.short_mavg.ix[buys.index], '^', markersize=4, color='m') ax2.plot(sells.index, perf.short_mavg.ix[sells.index], 'v', markersize=4, color='k') ax2.set_ylabel('price in $') plt.legend(loc=0) plt.show() plt.imsave("output.png")
def plot_generated_batch(X_full, X_sketch, generator_model, epoch_num, dataset_name, batch_num): # Generate images X_gen = generator_model.predict(X_sketch) X_sketch = inverse_normalization(X_sketch) X_full = inverse_normalization(X_full) X_gen = inverse_normalization(X_gen) # limit to 8 images as output Xs = X_sketch[:8] Xg = X_gen[:8] Xr = X_full[:8] # put |decoded, generated, original| images next to each other X = np.concatenate((Xs, Xg, Xr), axis=3) # make one giant block of images X = np.concatenate(X, axis=1) # save the giant n x 3 images plt.imsave('./pix2pix_out/progress_imgs/{}_epoch_{}_batch_{}.png'.format(dataset_name, epoch_num, batch_num), X[0], cmap='Greys_r')
def tensors_to_imgs(activations, save_dir, colormap='magma'): """save a list of activation tensors to disk as images""" date, time = get_date_time() for tensor in activations: layer_tag = 0 for i in range(tensor.size()[1] - 1): filename = '{}_{}_conv_{}_{}'.format(date, time, layer_tag, i) tensor_np = convert_display_Ttensor(tensor[i, :, :]) if i % 20 == 0: sleep(.1) plt.imsave(save_dir + filename, tensor_np, cmap=colormap) layer_tag += 1 #------------
def imsave(file_name, img): """ save a torch tensor as an image :param file_name: 'image/folder/image_name' :param img: 3*h*w torch tensor :return: nothing """ assert (type(img) == torch.FloatTensor, 'img must be a torch.FloatTensor') ndim = len(img.size()) assert (ndim == 2 or ndim == 3, 'img must be a 2 or 3 dimensional tensor') img = img.numpy() if ndim == 3: plt.imsave(file_name, np.transpose(img, (1, 2, 0))) else: plt.imsave(file_name, img, cmap='gray')
def saveImgs(xs, ys, save, colWidth=10): nImgs = xs.shape[0] assert(nImgs == ys.shape[0]) if not os.path.exists(save): os.makedirs(save) fnames = [] for i in range(nImgs): xy = np.clip(np.squeeze(np.concatenate([ys[i], xs[i]], axis=1)), 0., 1.) # Imagemagick montage has intensity scaling issues with png output files here. fname = "{}/{:04d}.jpg".format(save, i) plt.imsave(fname, xy, cmap=mpl.cm.gray) fnames.append(fname) os.system('montage -geometry +0+0 -tile {}x {} {}.png'.format( colWidth, ' '.join(fnames), save))
def plot_spectrogram(data, rate, name, dir_label): window_size = 2 ** 10 overlap = window_size // 8 window = sig.tukey(M=window_size, alpha=0.25) freq, time, spectrogram = sig.spectrogram(data, fs=rate, window=window, nperseg=window_size, scaling='density', noverlap=overlap) spectrogram = np.log10(np.flipud(spectrogram)) try: if spectrogram.shape[1] > 512: spec_padded = spectrogram[:512,:512] elif spectrogram.shape[1] < 512: spec_padded = np.pad(spectrogram, ((0, 0), (0, 512 - spectrogram.shape[1])), mode='median')[:512, :] else: spec_padded = spectrogram except Exception as e: print('ERROR!') print('Fault in: {}'.format(name)) raise spec_padded = transform.downscale_local_mean(spec_padded, (2, 2)) final_path = os.path.join(output_dir, dir_label, name + '.png') plt.imsave(final_path, spec_padded, cmap=plt.get_cmap('gray'))
def save(self, filename): plt.imsave(filename, self.data) # debug functions
def save(self, filename): ''' saves an image using the pyplot method''' plt.imsave(filename, self.data) # ------ operators overload ------
def imsave(file_name, img): """ save a torch tensor as an image :param file_name: 'image/folder/image_name' :param img: 3*h*w torch tensor :return: nothing """ assert(type(img) == torch.FloatTensor, 'img must be a torch.FloatTensor') ndim = len(img.size()) assert(ndim == 2 or ndim == 3, 'img must be a 2 or 3 dimensional tensor') img = img.numpy() if ndim == 3: plt.imsave(file_name, np.transpose(img, (1, 2, 0))) else: plt.imsave(file_name, img, cmap='gray')
def image_saver_callback(model, directory, epoch_interval=1, batch_interval=100, cmap='gray', render_videos=False): def save_image(weights, batch, layer_name, i): global current_epoch weight = str(i + 1).zfill(2) epoch = str(current_epoch).zfill(3) fold = os.path.join(directory, 'epoch_{}-layer_{}-weights_{}'.format(epoch, layer_name, weight)) if not os.path.isdir(fold): os.makedirs(fold) name = os.path.join('{}'.format(fold), '{}_{}x{}.png'.format(str(batch).zfill(9), weights.shape[0], weights.shape[1])) plt.imsave(name, weights, cmap=cmap) def save_weight_images(batch, logs): global current_epoch if current_epoch % epoch_interval == 0 and batch % batch_interval == 0: for layer in model.layers: if len(layer.get_weights()) > 0: for i, weights in enumerate(layer.get_weights()): if len(weights.shape) < 2: weights = np.expand_dims(weights, axis=0) save_image(weights, batch, layer.name, i) def on_epoch_begin(epoch, logs): global current_epoch current_epoch = epoch def on_train_end(logs): src = os.path.dirname(os.path.abspath(__file__)) cmd = os.path.join(src, '..', 'bin', 'create_image_sequence.sh') print(os.system('{} {}'.format(cmd, directory))) kwargs = dict() kwargs['on_batch_begin'] = save_weight_images kwargs['on_epoch_begin'] = on_epoch_begin if render_videos: kwargs['on_train_end'] = on_train_end return LambdaCallback(**kwargs)
def rgb_to_png(rgb): """convert RGB data from render to png""" sio = StringIO.StringIO() plt.imsave(sio, rgb) return sio.getvalue()
def write_img_to_png_file(img, filename): png_bytes = StringIO.StringIO() plt.imsave(png_bytes, img) print "writing", filename with open(filename, "w") as f: f.write(png_bytes.getvalue()) # some hacks for writing state to disk for visualisation
def Test(image_Name,flag): if(flag==False): saver = tf.train.Saver() saver = tf.train.import_meta_graph('Model Directory/our_model.meta') saver.restore(sess, 'Model Directory/our_model') GreyImagesRezied_Batch = [] OriginalImage_Batch=[] Original_Img = Image.open(TestingImgPath+image_Name).convert('RGB').convert('L') width,height=Original_Img.size Original_Img = Original_Img.resize((int(width/8) * 8,int(height/8) * 8),Image.ANTIALIAS) Grey_img = Original_Img.resize((224,224),Image.ANTIALIAS) Original_Img = np.asanyarray(Original_Img) Grey_img = np.asanyarray(Grey_img) img_shape = Original_Img.shape Original_reshaped = Original_Img.reshape(img_shape[0],img_shape[1], GreyChannels)#[H,W,1] OriginalImage_Batch.append(Original_reshaped)#[#imgs,224,224,1] img_reshaped = Grey_img.reshape(224, 224, GreyChannels)#[224,224,1] GreyImagesRezied_Batch.append(img_reshaped)#[#imgs,224,224,1] TestImage = tf.placeholder(dtype=tf.float32,shape=[1,224,224,1]) original = tf.placeholder(dtype=tf.float32,shape=[1,None,None,1]) Prediction = TestModel(original,TestImage,Original_Img.shape[0],Original_Img.shape[1]) Chrominance = sess.run(Prediction,feed_dict={TestImage:GreyImagesRezied_Batch,original:OriginalImage_Batch}) NewImg = np.empty((Original_Img.shape[0],Original_Img.shape[1],3)) for i in range(len(Original_reshaped[:,1,0])): for j in range(len(Original_reshaped[1,:,0])): NewImg[i,j,0]= 0 + ( (Original_reshaped[i,j,0] - 0) * (100 - 0) / (255 - 0) ) NewImg[:,:,1] = DeNormalize(Chrominance[0,:,:,0],0,1) NewImg[:,:,2] = DeNormalize(Chrominance[0,:,:,1],0,1) NewImg = color.lab2rgb(NewImg) plt.imsave(ResultImagePath+image_Name[0:-4]+"_Colored"+image_Name[len(image_Name)-4:],NewImg) #------------------------------------------------
def saveImage(image, imagepath, imageName, extension): plt.imsave(imagepath+'/'+imageName+'.'+extension,image) #---------------------------------------------------------------------------------------------- #Convolution Function
def save_pix2pix(unet, it, path, params): """Save the results of the pix2pix model.""" real_dir = join_and_create_dir(path, 'real') a_dir = join_and_create_dir(path, 'A') b_dir = join_and_create_dir(path, 'B') comp_dir = join_and_create_dir(path, 'composed') for i, filename in enumerate(it.filenames): a, b = next(it) bp = unet.predict(a) bp = convert_to_rgb(bp[0], is_binary=params.is_b_binary) img = compose_imgs(a[0], b[0], is_a_binary=params.is_a_binary, is_b_binary=params.is_b_binary) hi, wi, chi = img.shape hb, wb, chb = bp.shape if hi != hb or wi != 2*wb or chi != chb: raise Exception("Mismatch in img and bp dimensions {0} / {1}".format(img.shape, bp.shape)) composed = np.zeros((hi, wi+wb, chi)) composed[:, :wi, :] = img composed[:, wi:, :] = bp a = convert_to_rgb(a[0], is_binary=params.is_a_binary) b = convert_to_rgb(b[0], is_binary=params.is_b_binary) plt.imsave(open(os.path.join(real_dir, filename), 'wb+'), b) plt.imsave(open(os.path.join(b_dir, filename), 'wb+'), bp) plt.imsave(open(os.path.join(a_dir, filename), 'wb+'), a) plt.imsave(open(os.path.join(comp_dir, filename), 'wb+'), composed)
def check_accuracy(model, loader,epoch, dtype, visualize = False): """ Check the accuracy of the model. """ num_correct, num_samples = 0, 0 for x,z,y in loader: x_var = Variable(x.type(dtype),volatile=True) z_var = Variable(z.type(dtype),volatile=True) pred_depth,pred_labels = model(x_var,z_var) _,preds = pred_labels.data.cpu().max(1) if visualize == True: #Save the input RGB image, Ground truth depth map, Ground Truth Coloured Semantic Segmentation Map, #Predicted Coloured Semantic Segmentation Map, Predicted Depth Map for one image in the current batch input_rgb_image = x_var[0].data.permute(1,2,0).cpu().numpy().astype(np.uint8) plt.imsave('input_rgb_epoch_{}.png'.format(epoch),input_rgb_image) input_gt_depth_image = z_var[0].data.permute(1,2,0).cpu().numpy().astype(np.uint8) plt.imsave('input_gt_depth_epoch_{}.png'.format(epoch),input_gt_depth_image) colored_gt_label = color[y[0].squeeze().cpu().numpy().astype(int)].astype(np.uint8) plt.imsave('gt_label_epoch_{}.png'.format(epoch),colored_gt_label) colored_pred_label = color[preds[0].squeeze().cpu().numpy().astype(int)].astype(np.uint8) plt.imsave('pred_label_epoch_{}.png'.format(epoch),colored_pred_label) pred_depth_image = pred_depth[0].data.squeeze().cpu().numpy().astype(np.uint8) plt.imsave('pred_depth_epoch_{}.png'.format(epoch),pred_depth_image,cmap = "gray") # Computing pixel-wise accuracy num_correct += (preds.long() == y.long()).sum() num_samples += preds.numel() acc = float(num_correct) / num_samples return acc
def plot_linear_stretch(M, path, R, G, B, suffix=None): """ Plot a linear stretched RGB image. Parameters: M: `numpy array` A HSI cube (m x n x p). path: `string` The path where to put the plot. R: `int` A band number that will render the red color. G: `int` A band number that will render the green color. B: `int` A band number that will render the blue color. suffix: `string [default None]` Add a suffix to the file name. """ img = _linear_stretch(M, R, G, B) plt.ioff() if suffix == None: fout = osp.join(path, 'linear_stretch.png') else: fout = osp.join(path, 'linear_stretch_{0}.png'.format(suffix)) plt.imsave(fout, img) plt.close()
def montage(images, saveto='montage.png'): """Draw all images as a montage separated by 1 pixel borders. Also saves the file to the destination specified by `saveto`. Parameters ---------- images : numpy.ndarray Input array to create montage of. Array should be: batch x height x width x channels. saveto : str Location to save the resulting montage image. Returns ------- m : numpy.ndarray Montage image. """ if isinstance(images, list): images = np.array(images) img_h = images.shape[1] img_w = images.shape[2] n_plots = int(np.ceil(np.sqrt(images.shape[0]))) if len(images.shape) == 4 and images.shape[3] == 3: m = np.ones( (images.shape[1] * n_plots + n_plots + 1, images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5 else: m = np.ones( (images.shape[1] * n_plots + n_plots + 1, images.shape[2] * n_plots + n_plots + 1)) * 0.5 for i in range(n_plots): for j in range(n_plots): this_filter = i * n_plots + j if this_filter < images.shape[0]: this_img = images[this_filter] m[1 + i + i * img_h:1 + i + (i + 1) * img_h, 1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_img plt.imsave(arr=m, fname=saveto) return m
def montage_filters(W, saveto='montage.png'): """Draws all filters (n_input * n_output filters) as a montage image separated by 1 pixel borders. Parameters ---------- W : Tensor Input tensor to create montage of. Returns ------- m : numpy.ndarray Montage image. """ W = np.reshape(W, [W.shape[0], W.shape[1], 1, W.shape[2] * W.shape[3]]) n_plots = int(np.ceil(np.sqrt(W.shape[-1]))) m = np.ones( (W.shape[0] * n_plots + n_plots + 1, W.shape[1] * n_plots + n_plots + 1)) * 0.5 for i in range(n_plots): for j in range(n_plots): this_filter = i * n_plots + j if this_filter < W.shape[-1]: m[1 + i + i * W.shape[0]:1 + i + (i + 1) * W.shape[0], 1 + j + j * W.shape[1]:1 + j + (j + 1) * W.shape[1]] = ( np.squeeze(W[:, :, :, this_filter])) plt.imsave(arr=m, fname=saveto) return m
def make_noise(index): h = np.random.randint(1, H_IMG) w = np.random.randint(1, W_IMG) noise = np.random.random((h, w)) noisy_img = cv2.resize(noise, (H_IMG, W_IMG), interpolation=cv2.INTER_CUBIC) fx = float(w) / float(W_IMG) fy = float(h) / float(H_IMG) filename = '{}/{:0>5d}_{}_{}.jpg'.format(SAMPLES_DIR, index, fx, fy) plt.imsave(filename, noisy_img, cmap='gray')
def montage(images, saveto='montage.png'): """Draw all images as a montage separated by 1 pixel borders. Also saves the file to the destination specified by `saveto`. Parameters ---------- images : numpy.ndarray Input array to create montage of. Array should be: batch x height x width x channels. saveto : str Location to save the resulting montage image. Returns ------- m : numpy.ndarray Montage image. """ if isinstance(images, list): images = np.array(images) img_h = images.shape[1] img_w = images.shape[2] n_plots = int(np.ceil(np.sqrt(images.shape[0]))) if len(images.shape) == 4 and images.shape[3] == 3: m = np.ones( (images.shape[1] * n_plots + n_plots + 1, images.shape[2] * n_plots + n_plots + 1, 3)) * 0.5 else: m = np.ones( (images.shape[1] * n_plots + n_plots + 1, images.shape[2] * n_plots + n_plots + 1)) * 0.5 for i in range(n_plots): for j in range(n_plots): this_filter = i * n_plots + j if this_filter < images.shape[0]: this_img = images[this_filter] #print(this_img.shape, m.shape) m[1 + i + i * img_h:1 + i + (i + 1) * img_h, 1 + j + j * img_w:1 + j + (j + 1) * img_w] = this_img.squeeze() plt.imsave(arr=m, fname=saveto) return m
def test_simple(params): """Test function.""" left = tf.placeholder(tf.float32, [2, args.input_height, args.input_width, 3]) model = MonodepthModel(params, "test", left, None) input_image = scipy.misc.imread(args.image_path, mode="RGB") original_height, original_width, num_channels = input_image.shape input_image = scipy.misc.imresize(input_image, [args.input_height, args.input_width], interp='lanczos') input_image = input_image.astype(np.float32) / 255 input_images = np.stack((input_image, np.fliplr(input_image)), 0) # SESSION config = tf.ConfigProto(allow_soft_placement=True) sess = tf.Session(config=config) # SAVER train_saver = tf.train.Saver() # INIT sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) coordinator = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coordinator) # RESTORE restore_path = args.checkpoint_path.split(".")[0] train_saver.restore(sess, restore_path) disp = sess.run(model.disp_left_est[0], feed_dict={left: input_images}) disp_pp = post_process_disparity(disp.squeeze()).astype(np.float32) output_directory = os.path.dirname(args.image_path) output_name = os.path.splitext(os.path.basename(args.image_path))[0] np.save(os.path.join(output_directory, "{}_disp.npy".format(output_name)), disp_pp) disp_to_img = scipy.misc.imresize(disp_pp.squeeze(), [original_height, original_width]) plt.imsave(os.path.join(output_directory, "{}_disp.png".format(output_name)), disp_to_img, cmap='plasma') print('done!')
def feedforward(self, image): prev_activation = image # forwardpass for layer in self.layers: input_to_feed = prev_activation if isinstance(layer, FullyConnectedLayer): # z values are huge, while the fc_output is tiny! large negative vals get penalized to 0! layer.feedforward(input_to_feed) elif isinstance(layer, ConvLayer): layer.convolve(input_to_feed) for i in range(layer.output.shape[0]): plt.imsave('images/cat_conv%d.jpg'%i, layer.output[i]) for i in range(layer.weights.shape[0]): plt.imsave('images/filter_conv%s.jpg'%i, layer.weights[i].reshape((5,5))) elif isinstance(layer, PoolingLayer): layer.pool(input_to_feed) for i in range(layer.output.shape[0]): plt.imsave('images/pool_pic%s.jpg'%i, layer.output[i]) elif isinstance(layer, ClassifyLayer): layer.classify(input_to_feed) else: raise NotImplementedError prev_activation = layer.output final_activation = prev_activation return final_activation
def img_to_summary(img, tag="img"): s = StringIO() plt.imsave(s, img, cmap='bone', format='png') summary = tf.Summary.Value(tag=tag, image=tf.Summary.Image(encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1])) return summary
def save(self, layer_id, filter_id, img): directory = '{}/{}/{}'.format(self.save_dir_, layer_id, filter_id) if not os.path.exists(directory): os.makedirs(directory) filepath = os.path.join(directory,'img.jpg') plt.imsave(filepath, img)
def __init__(self, global_counter, path_to_mha=None, how_many_from_one=1, saving_path='./test_data/'): if path_to_mha is None: raise NameError(' missing .mha path ') self.images = [] for i in range(0, len(path_to_mha)): self.images.append(np.array(sitk.GetArrayFromImage(sitk.ReadImage(path_to_mha[i])))) mkdir_p(saving_path) plt.set_cmap('gray') while how_many_from_one > 0: image_to_save = np.zeros((5, 216, 160)) rand_value = rnd.randint(30, len(self.images[0]) - 30) for i in range(0, len(path_to_mha)): try: image_to_save[i] = self.images[i][rand_value] except: print('ahi') print(self.images[i][rand_value].shape) print(type(self.images)) print(type(self.images)) print('*') continue print(image_to_save.shape) image_to_save = image_to_save.reshape((216 * 5, 160)) print(image_to_save.shape) # image_to_save = resize(image_to_save, (5*216, 160), mode='constant') # image_to_save = image_to_save.resize(5*216, 160) plt.imsave(saving_path + str(global_counter) + '.png', image_to_save) global_counter += 1 how_many_from_one -= 1
def generate_images_line_save(self, line_segment, query_id, image_original_space=None): """ ID of query point from which query line was generated is added to the filename of the saved line query. :param line_segment: :param query_id: :return: """ try: if image_original_space is not None: x = self.generative_model.decode(image_original_space.T) else: x = self.generative_model.decode(to_vector(self.dataset.data["features"][ query_id]).T) # comes from dataset.data["features"], so is already in original space in which ALI operates. save_path = os.path.join(self.save_path_queries, "pointquery_%d_%d.png" % (self.n_queries + 1, query_id)) if x.shape[1] == 1: plt.imsave(save_path, x[0, 0, :, :], cmap=cm.Greys) else: plt.imsave(save_path, x[0, :, :, :].transpose(1, 2, 0), cmap=cm.Greys_r) decoded_images = self.generative_model.decode(self.dataset.scaling_transformation.inverse_transform( line_segment)) # Transform to original space, in which ALI operates. figure = plt.figure() grid = ImageGrid(figure, 111, (1, decoded_images.shape[0]), axes_pad=0.1) for image, axis in zip(decoded_images, grid): if image.shape[0] == 1: axis.imshow(image[0, :, :].squeeze(), cmap=cm.Greys, interpolation='nearest') else: axis.imshow(image.transpose(1, 2, 0).squeeze(), cmap=cm.Greys_r, interpolation='nearest') axis.set_yticklabels(['' for _ in range(image.shape[1])]) axis.set_xticklabels(['' for _ in range(image.shape[2])]) axis.axis('off') save_path = os.path.join(self.save_path_queries, "linequery_%d_%d.pdf" % (self.n_queries + 1, query_id)) plt.savefig(save_path, transparent=True, bbox_inches='tight') except Exception as e: print "EXCEPTION:", traceback.format_exc() raise e
def images_clip(fold): onlyfiles = listdir_files(fold) fold_clip = fold + '_clip' # Generate a new path to save clipping images if not os.path.exists(fold_clip): os.makedirs(fold_clip) for fname in onlyfiles: pf = os.path.join(fold, fname) iac = image_clip(pf) fname_clip = os.path.join(fold_clip, fname[:-4] + '_clip.tif') print(fname_clip) plt.imsave(fname_clip, iac, cmap='gray')
def save_decisions(model: keras.models.Model, experiences: Iterable[Experience]): for i, (img, probabilities) in enumerate(images_with_probabilities(model, experiences)): img = _min_max_normalize(img) img = add_decision_boundaries(img, probabilities) plt.imsave('decisions/d{}.png'.format(i), img, origin='lower')
def _step(self, action): obs, reward, done, info = self.env.step(action) location = info.get('location') if location is not None: """ self.locations.append(location) if len(self.locations) == self.buffer_size: # rebuild the kde self.kde = stats.gaussian_kde(np.array(self.locations).T, self.bandwidth) # plot it? dims = obs.shape[:2] grid = np.indices(dims) kde = self.kde.logpdf(grid.reshape([2, -1])) kde = kde.reshape(dims) info['kde'] = kde #plt.imsave('test.png', kde) # drop the older locations self.locations = self.locations[self.buffer_size//2:] #plt.imsave('counts.png', self.counts) #info['logprob'] = logprob if self.kde: logpdf = self.kde.logpdf(np.array(location)) info['logpdf'] = logpdf reward -= logpdf """ location = location + self.breadth # padding index = tuple(location.tolist()) patch = extract_patch(self.counts, index, self.breadth) count = (self.kernel * patch).sum() info['log/visits'] = count logprob = np.log(count / self.total) info['log/visit_logprob'] = logprob #reward = 0 bonus = self.explore_scale * (self.logprob - logprob) info['log/explore_bonus'] = np.abs(bonus) reward += bonus self.logprob = logprob if self.decay: self.counts *= self.decay else: self.total += 1 self.counts[index] += 1 return obs, reward, done, info
def val(): color_model.eval() i = 0 for data, _ in val_loader: original_img = data[0].unsqueeze(1).float() gray_name = './gray/' + str(i) + '.jpg' for img in original_img: pic = img.squeeze().numpy() pic = pic.astype(np.float64) plt.imsave(gray_name, pic, cmap='gray') w = original_img.size()[2] h = original_img.size()[3] scale_img = data[1].unsqueeze(1).float() if have_cuda: original_img, scale_img = original_img.cuda(), scale_img.cuda() original_img, scale_img = Variable(original_img, volatile=True), Variable(scale_img) _, output = color_model(original_img, scale_img) color_img = torch.cat((original_img, output[:, :, 0:w, 0:h]), 1) color_img = color_img.data.cpu().numpy().transpose((0, 2, 3, 1)) for img in color_img: img[:, :, 0:1] = img[:, :, 0:1] * 100 img[:, :, 1:3] = img[:, :, 1:3] * 255 - 128 img = img.astype(np.float64) img = lab2rgb(img) color_name = './colorimg/' + str(i) + '.jpg' plt.imsave(color_name, img) i += 1 # use the follow method can't get the right image but I don't know why # color_img = torch.from_numpy(color_img.transpose((0, 3, 1, 2))) # sprite_img = make_grid(color_img) # color_name = './colorimg/'+str(i)+'.jpg' # save_image(sprite_img, color_name) # i += 1
def test_simple(params, image_path, out_dir_path): """Test function.""" input_image = scipy.misc.imread(args.image_path) try: original_height, original_width, num_channels = input_image.shape except ValueError as e: original_height, original_width = input_image.shape num_channels = 1 left = tf.placeholder(tf.float32, [2, args.input_height, args.input_width, 3]) model = MonodepthModel(params, "test", left, None) if num_channels == 4: input_image = input_image[:,:,:3] elif num_channels == 1: input_image = np.tile((input_image, input_image, input_image), 2) input_image = scipy.misc.imresize(input_image, [args.input_height, args.input_width], interp='lanczos') input_image = input_image.astype(np.float32) / 255 input_images = np.stack((input_image, np.fliplr(input_image)), 0) # SESSION config = tf.ConfigProto(allow_soft_placement=True) sess = tf.Session(config=config) # SAVER train_saver = tf.train.Saver() # INIT sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) coordinator = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coordinator) # RESTORE restore_path = args.checkpoint_path train_saver.restore(sess, restore_path) disp = sess.run(model.disp_left_est[0], feed_dict={left: input_images}) disp_pp = post_process_disparity(disp.squeeze()).astype(np.float32) depth = 1 - disp_pp depth = depth / np.amax(depth) output_name = os.path.splitext(os.path.basename(args.image_path))[0] depth_to_img = scipy.misc.imresize(depth, [original_height, original_width]) output_path = os.path.join(out_dir_path, "{}_depth.png".format(output_name)) plt.imsave(output_path, depth_to_img, cmap='gray') return output_path
def fit(self, X_train, X_val, n_epoch=10, n_batch=128, logdir='dcgan-run'): # initialize log directory if tf.gfile.Exists(logdir): tf.gfile.DeleteRecursively(logdir) tf.gfile.MakeDirs(logdir) # create a saver checkpoint_root = os.path.join(logdir, 'model.ckpt') saver = tf.train.Saver() # # summarization # summary = tf.summary.merge_all() # summary_writer = tf.summary.FileWriter(self.logdir, self.sess.graph) # init model init = tf.global_variables_initializer() self.sess.run(init) # train the model step = 0 for epoch in xrange(n_epoch): start_time = time.time() for X_batch in iterate_minibatches(X_train, n_batch, shuffle=True): step += 1 # load the batch noise = np.random.rand(n_batch,100).astype('float32') feed_dict = self.load_batch(X_batch, noise) # take training step # self.train_g(feed_dict) # self.train_d(feed_dict) self.train(feed_dict) # log results at the end of batch tr_g_err, tr_d_err, tr_p_real, tr_p_fake = self.eval_err(X_train) va_g_err, va_d_err, va_p_real, va_p_fake = self.eval_err(X_val) print "Epoch {} of {} took {:.3f}s ({} minibatches)".format( epoch + 1, n_epoch, time.time() - start_time, len(X_train) // n_batch) print " training disc_loss/gen_loss/p_real/p_fake:\t\t{:.4f}\t{:.4f}\t{:.2f}\t{:.2f}".format( tr_g_err, tr_d_err, tr_p_real, tr_p_fake) print " validation disc_loss/gen_loss/p_real/p_fake:\t\t{:.4f}\t{:.4f}\t{:.2f}\t{:.2f}".format( va_g_err, va_d_err, va_p_real, va_p_fake) # take samples samples = self.gen(np.random.rand(128, 100).astype('float32')) samples = samples[:42] fname = logdir + '/dcgan.mnist_samples-%d.png' % (epoch+1) plt.imsave(fname, (samples.reshape(6, 7, 28, 28) .transpose(0, 2, 1, 3) .reshape(6*28, 7*28)), cmap='gray') saver.save(self.sess, checkpoint_root, global_step=step)
def fit(self, X_train, X_val, n_epoch=10, n_batch=128, logdir='dcgan-run'): # initialize log directory if tf.gfile.Exists(logdir): tf.gfile.DeleteRecursively(logdir) tf.gfile.MakeDirs(logdir) mnist = input_data.read_data_sets('data/mnist') # init model init = tf.global_variables_initializer() self.sess.run(init) # train the model step, g_step, epoch = 0, 0, 0 while mnist.train.epochs_completed < n_epoch: n_critic = 100 if g_step < 25 or (g_step+1) % 500 == 0 else self.n_critic start_time = time.time() for i in range(n_critic): losses_d = [] # load the batch X_batch = mnist.train.next_batch(n_batch)[0] X_batch = X_batch.reshape((n_batch, 1, 28, 28)) noise = np.random.rand(n_batch,100).astype('float32') feed_dict = self.load_batch(X_batch, noise) # train the critic/discriminator loss_d = self.train_d(feed_dict) losses_d.append(loss_d) loss_d = np.array(losses_d).mean() # train the generator noise = np.random.rand(n_batch,100).astype('float32') # noise = np.random.uniform(-1.0, 1.0, [n_batch, 100]).astype('float32') feed_dict = self.load_batch(X_batch, noise) loss_g = self.train_g(feed_dict) g_step += 1 if g_step < 100 or g_step % 100 == 0: tot_time = time.time() - start_time print 'Epoch: %3d, Gen step: %4d (%3.1f s), Disc loss: %.6f, Gen loss %.6f' % \ (mnist.train.epochs_completed, g_step, tot_time, loss_d, loss_g) # take samples if g_step % 100 == 0: noise = np.random.rand(n_batch,100).astype('float32') samples = self.gen(noise) samples = samples[:42] fname = logdir + '.mnist_samples-%d.png' % g_step plt.imsave(fname, (samples.reshape(6, 7, 28, 28) .transpose(0, 2, 1, 3) .reshape(6*28, 7*28)), cmap='gray') # saver.save(self.sess, checkpoint_root, global_step=step)