我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用matplotlib.image.imsave()。
def compare_image_lists(new_result, old_result, decimals): fns = [] for i in range(2): tmpfd, tmpname = tempfile.mkstemp(suffix='.png') os.close(tmpfd) fns.append(tmpname) num_images = len(old_result) assert(num_images > 0) for i in range(num_images): mpimg.imsave(fns[0], np.loads(zlib.decompress(old_result[i]))) mpimg.imsave(fns[1], np.loads(zlib.decompress(new_result[i]))) results = compare_images(fns[0], fns[1], 10**(-decimals)) if results is not None: if os.environ.get("JENKINS_HOME") is not None: tempfiles = [line.strip() for line in results.split('\n') if line.endswith(".png")] for fn in tempfiles: sys.stderr.write("\n[[ATTACHMENT|{}]]".format(fn)) sys.stderr.write('\n') assert_equal(results, None, results) for fn in fns: os.remove(fn)
def make_liposomes(lip_class, n, out_dir): """ :param lip_class: :param n: :param out_dir: :return: """ try: os.makedirs(out_dir) except OSError as exc: if exc.errno != errno.EEXIST: raise for i in xrange(n): liposome = lip_class(128, 128, prob_deviation=0.5) liposome.make() img_name = '{}.png'.format(i + 1) img_path = os.path.join(out_dir, img_name) print('\rSaving {}'.format(img_path), end='') mpimg.imsave(img_path, liposome.data, cmap='Greys_r', vmin=0, vmax=1)
def convert_pgm_to_png(): images = [] for i, row in normal.iterrows(): images.append(read_pgm('./mias/pgm/' + row['reference_number'] + '.pgm')) j = 0; for i, row in normal.iterrows(): images[j].setflags(write=1) if (int(row['reference_number'][-3:]) % 2 == 0): images[j][:324, 700:1024] = np.zeros((324, 324)) else: images[j][:324, :324] = np.zeros((324, 324)) matlabimg.imsave('./mias/png/' + row['reference_number'] + '.png', images[j], vmin=0, vmax=255, cmap='gray') j += 1
def convert_pgm_to_png_anomalous(): images = [] for i, row in abnormal.iterrows(): images.append(read_pgm('./mias/pgm/' + row['reference_number'] + '.pgm')) j = 0; for i, row in abnormal.iterrows(): images[j].setflags(write=1) if (int(row['reference_number'][-3:]) % 2 == 0): images[j][:324, 700:1024] = np.zeros((324, 324)) else: images[j][:324, :324] = np.zeros((324, 324)) matlabimg.imsave('./mias/png_anomalous/' + row['reference_number'] + '.png', images[j], vmin=0, vmax=255, cmap='gray') j += 1
def generate_patches(input_image): # print("in generate patchhes") global global_counter input_image = crop_center(input_image, 384, 384) patches = image.extract_patches_2d(input_image, patch_size, max_patches=50, random_state=rng) for counter, i in enumerate(patches): if np.any(i): matlabimg.imsave('./data/mias_anomalous/' + str(global_counter) + '.png', i, cmap='gray') global_counter += 1 # # convert_pgm_to_png_anomalous()
def ColorSelector(): # Read in the image and print out some stats image = (mpimg.imread('test.png') * 255).astype('uint8') print('This image is: ', type(image), 'with dimensions:', image.shape) # Grab the x and y size and make a copy of the image ysize = image.shape[0] xsize = image.shape[1] color_select = np.copy(image) # Define color selection criteria # MODIFY THESE VARIABLES TO MAKE YOUR COLOR SELECTION red_threshold = 200 green_threshold = 200 blue_threshold = 200 rgb_threshold = [red_threshold, green_threshold, blue_threshold] print('Esta es la variable rgb_threshold: ', rgb_threshold) # Do a bitwise or with the "|" character to identify # pixels below the thresholds thresholds = (image[:, :, 0] < rgb_threshold[0]) \ | (image[:, :, 1] < rgb_threshold[1]) \ | (image[:, :, 2] < rgb_threshold[2]) print('Esta es la variable thresholds: ', thresholds) color_select[thresholds] = [0, 0, 0] # plt.imshow(color_select) # Uncomment the following code if you are running the code # locally and wish to save the image mpimg.imsave("test-after.png", color_select) # Display the image plt.imshow(color_select) plt.show()
def showPicture(test_length, path): if not os.path.exists(path): os.makedirs(path) data_gen.init_data(task, test_length, 1, n_input) while len(data_gen.train_set[task][test_length])==0: test_length += 1 data_gen.init_data(task, test_length, 1, n_input) data_gen.resetCounters() with tf.Graph().as_default(),tf.device('/cpu:0'): tester = DNGPU(n_hidden, [test_length], n_input, [1], n_output, dropout_keep_prob) tester.createTestGraph(test_length) saver = tf.train.Saver(tf.trainable_variables()) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver.restore(sess, model_file) if not os.path.exists(path): os.makedirs(path) batch_xs, batch_ys = genTestData(test_length, 1) print(batch_xs, batch_ys) mem = tester.getAllMem(sess, batch_xs, batch_ys) mem = np.squeeze(mem, 1) width = mem.shape[1] height = mem.shape[0] for unit in range(n_hidden): img=np.zeros((height,width),dtype=np.float32) for x in range(width): for y in range(height): img[y,x]=mem[y, x,unit] mpimg.imsave(path+"/frame"+str(unit)+".png",img, cmap='gray') #Perform training
def saveVideo(I, IDims, filename, FrameRate = 30, YCbCr = False, Normalize = False): #Overwrite by default if os.path.exists(filename): os.remove(filename) N = I.shape[0] if YCbCr: for i in range(N): frame = np.reshape(I[i, :], IDims) I[i, :] = ntsc2rgb(frame).flatten() if Normalize: I = I-np.min(I) I = I/np.max(I) for i in range(N): frame = np.reshape(I[i, :], IDims) frame[frame < 0] = 0 frame[frame > 1] = 1 mpimage.imsave("%s%i.png"%(TEMP_STR, i+1), frame) if os.path.exists(filename): os.remove(filename) #Convert to video using avconv command = [AVCONV_BIN, '-r', "%i"%FrameRate, '-i', TEMP_STR + '%d.png', '-r', "%i"%FrameRate, '-b', '30000k', filename] subprocess.call(command) #Clean up for i in range(N): os.remove("%s%i.png"%(TEMP_STR, i+1)) ############################################################# #### SLIDING WINDOW VIDEO TOOLS, GENERAL ##### #############################################################
def save_image(I, filename): """save image to file :param I: image to save :param filename: filename where the image will be saved """ mpimg.imsave(filename, I)
def displayAndSaveImage(img, path): plt.imshow(img) mpimg.imsave(path, img)
def saveImageWithCmap(img, path, cmap): mpimg.imsave(path, img, cmap=cmap)
def writeout(self): """Method to save stored data to images. """ for i,I in self.items.items(): current_frame = (self.current_frame - I['offset']) % (I['offset'] + 1) savefile = self.save_path + os.sep + i + os.sep + str(self.current_frame).rjust(8, '0') + '.png' item_shape = self.net['neuron_pools'][i]['shape'] if item_shape[0] == 1: dat = self.store_data[i][current_frame][0,:,:] elif item_shape[0] == 2: dat = None elif item_shape[0] == 3: dat = np.swapaxes(self.store_data[i][current_frame], 0, 2) Image.imsave(savefile, dat)
def save_image(self, tensor, name='default.jpg'): image = tensor.clone().cpu() image = image.view(3, image_size, image_size) image = self.un_loader(image) print(image) try: im = Image.fromarray(image) im.save(name) print('image saved.') except Exception as e: print(e) mimage.imsave(name, image) print('image saved.')
def save_hsd_img(hsd,name): path = cfg.config_path() outs_path = os.path.join(path.top_dir,path.hsd_dir,name) img_dat = hsd_t.hsd2rgb(hsd) mpimg.imsave(outs_path,img_dat) return 0
def save_svm_images(model_dict, data_dict, X_test, adv_x, dev_mag, rd=None, dr_alg=None, rev=None): """ Save <no_of_img> adv. samples as image files in visual_data folder """ no_of_img = 1 # Number of images to save indices = range(no_of_img) dataset = model_dict['dataset'] DR = model_dict['dim_red'] channels = model_dict['channels'] abs_path_v = resolve_path_v(model_dict) no_of_features = data_dict['no_of_features'] height = data_dict['height'] width = data_dict['width'] for i in indices: if channels == 1: adv = adv_x[i].reshape((height, width)) orig = X_test[i].reshape((height, width)) cmap = 'gray' else: adv = adv_x[i].reshape((channels, height, width)) adv = adv.swapaxes(0, 2).swapaxes(0, 1) orig = X_test[i].reshape((channels, height, width)) orig = orig.swapaxes(0, 2).swapaxes(0, 1) cmap = None fname = abs_path_v if (rd is not None) and (rev is None): fname += '{}_{}_{}'.format(i, DR, rd) elif rd is not None: fname += '{}_{}_rev_{}'.format(i, DR, rd) elif rd is None: fname += '{}'.format(i) img.imsave(fname + '_mag{}.png'.format(dev_mag), adv, vmin=0, vmax=1, cmap=cmap) img.imsave(fname + '_orig.png', orig, vmin=0, vmax=1, cmap=cmap) #------------------------------------------------------------------------------#