Python matplotlib.pyplot.imsave() Examples

The following are 30 code examples of matplotlib.pyplot.imsave(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib.pyplot , or try the search function .
Example #1
Source File: vis_hooks.py    From DenseMatchingBenchmark with MIT License 8 votes vote down vote up
def prepare_visualize(result, epoch, work_dir, image_name):
    result_tool = ShowResultTool()
    result = result_tool(result)
    mkdir_or_exist(os.path.join(work_dir, image_name))
    save_path = os.path.join(work_dir, image_name, '{}.png'.format(epoch))
    plt.imsave(save_path, result['GroupColor'], cmap=plt.cm.hot)

    log_result = {}
    for pred_item in result.keys():
        log_name = image_name + '/' + pred_item
        if pred_item == 'Flow':
            log_result['image/' + log_name] = result[pred_item]
        if pred_item == 'GroundTruth':
            log_result['image/' + log_name] = result[pred_item]

    return log_result 
Example #2
Source File: tensorboard_logging.py    From lsm with MIT License 7 votes vote down vote up
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)
        self.writer.flush() 
Example #3
Source File: SIFT.py    From image-processing-from-scratch with MIT License 7 votes vote down vote up
def drawLines(X1,X2,Y1,Y2,dis,img,num = 10):

    info = list(np.dstack((X1,X2,Y1,Y2,dis))[0])
    info = sorted(info,key=lambda x:x[-1])
    info = np.array(info)
    info = info[:min(num,info.shape[0]),:]
    img = Lines(img,info)
    #plt.imsave('./sift/3.jpg', img)

    if len(img.shape) == 2:
        plt.imshow(img.astype(np.uint8),cmap='gray')
    else:
        plt.imshow(img.astype(np.uint8))
    plt.axis('off')
    #plt.plot([info[:,0], info[:,1]], [info[:,2], info[:,3]], 'c')
    # fig = plt.gcf()
    # fig.set_size_inches(int(img.shape[0]/100.0),int(img.shape[1]/100.0))
    #plt.savefig('./sift/2.jpg')
    plt.show() 
Example #4
Source File: scale_two.py    From Text-Recognition with GNU Lesser General Public License v2.1 6 votes vote down vote up
def _custom_get(self, i, no, all_returns):

		for dataset_name, d in self.datasets_attr.items():
			if d['range'][0] <= i and d['range'][1] > i:
				image_root = d['image_root']
				d_name = dataset_name
				break

		image_new, link_new, target_new, weight_new, contour_i = self.aspect_resize(self.loader(image_root+'/'+self.images[i]), self.annots[i].copy(), self.remove_annots[i].copy())#, big_target_new
		image_new, target_new, link_new, contour_i = self.rotate(image_new, target_new, link_new, contour_i, 90)
		show = True
		if show:
			plt.imsave('img.png',image_new)
			num = np.array(image_new)
			cv2.drawContours(num, contour_i, -1, (0,255,0), 3)
			plt.imsave('contours.png',num)
			plt.imsave('target.png',target_new)
		img = self.transform(image_new).unsqueeze(0)
		target = self.target_transform(target_new).unsqueeze(0)
		link = self.target_transform(link_new).unsqueeze(0)
		weight = torch.FloatTensor(weight_new).unsqueeze(0).unsqueeze(0)
		all_returns[no] = [img, target, link, weight, contour_i, d_name] 
Example #5
Source File: map_train.py    From doom-net-pytorch with MIT License 6 votes vote down vote up
def draw(distance, objects, file_name):
    distance = distance.view(-1).cpu().numpy()
    objects = objects.view(-1).cpu().numpy()

    distance = np.around(distance / 4.0)
    distance[distance > 15] = 15

    screen = np.zeros([DoomObject.Type.MAX, 16, 32], dtype=np.float32)
    x = np.around(16 + tan * distance).astype(int)
    y = np.around(distance).astype(int)
    todelete = np.where(y == 15)
    y = np.delete(y, todelete, axis=0)
    x = np.delete(x, todelete, axis=0)
    channels = np.delete(objects, todelete, axis=0)
    screen[channels, y, x] = 1

    img = screen[[8, 7, 6], :]
    img = img.transpose(1, 2, 0)
    plt.imsave(file_name, img) 
Example #6
Source File: meta_artificial.py    From Text-Recognition with GNU Lesser General Public License v2.1 6 votes vote down vote up
def create_annot1(self):

		all_paths = self.get_all_names_refresh()

		for i in all_paths:

			if os.path.exists(self.label_save_location+'.'.join(i.split('.')[:-1])+'.pkl'):
				continue
			print(i)
			image = Image.open(self.image_net_location+i).resize([768, 512]).convert('RGB')
			image = self.transparent(np.array(image),self.transparent_mean,self.transparent_gaussian)
			image = Image.fromarray(image.astype(np.uint8))
			final_image, coordinate_label ,label=self.generate_watermark_on_images(image)
			
			with open(self.label_save_location+'.'.join(i.split('.')[:-1])+'.pkl', 'wb') as f:
				pickle.dump([coordinate_label, label], f)
			plt.imsave(self.image_save_location+i, final_image) 
Example #7
Source File: nanotron.py    From picasso with MIT License 6 votes vote down vote up
def prepare_data(locs, label, pick_radius,
                 oversampling, alpha=10,
                 bg=1, export=False):

    img_shape = int(2 * pick_radius * oversampling)
    data = []
    labels = []

    for pick in tqdm(range(locs.group.max()), desc='Prepare '+str(label)):

        pick_img = roi_to_img(locs, pick,
                              radius=pick_radius,
                              oversampling=oversampling)

        if export is True and pick < 10:
            filename = 'label' + str(label) + '-' + str(pick)
            plt.imsave('./img/' + filename + '.png', (alpha*pick_img-bg), cmap='Greys', vmax=10)

        pick_img = prepare_img(pick_img, img_shape=img_shape, alpha=alpha, bg=bg)

        data.append(pick_img)
        labels.append(label)

    return data, label 
Example #8
Source File: visualisation.py    From variational-continual-learning with Apache License 2.0 6 votes vote down vote up
def plot_images(images, shape, path, filename, n_rows = 10, color = True):
     # finally save to file
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    images = reshape_and_tile_images(images, shape, n_rows)
    if color:
        from matplotlib import cm
        plt.imsave(fname=path+filename+".png", arr=images, cmap=cm.Greys_r)
    else:
        plt.imsave(fname=path+filename+".png", arr=images, cmap='Greys')
    #plt.axis('off')
    #plt.tight_layout()
    #plt.savefig(path + filename + ".png", format="png")
    print "saving image to " + path + filename + ".png"
    plt.close() 
Example #9
Source File: save_result.py    From DenseMatchingBenchmark with MIT License 6 votes vote down vote up
def __call__(self, result, out_dir, image_name):
        result_tool = ShowResultTool()
        result = result_tool(result, color_map='gray', bins=100)

        if 'GrayDisparity' in result.keys():
            grayEstDisp = result['GrayDisparity']
            gray_save_path = osp.join(out_dir, 'disp_0')
            mkdir_or_exist(gray_save_path)
            skimage.io.imsave(osp.join(gray_save_path, image_name), (grayEstDisp * 256).astype('uint16'))

        if 'ColorDisparity' in result.keys():
            colorEstDisp = result['ColorDisparity']
            color_save_path = osp.join(out_dir, 'color_disp')
            mkdir_or_exist(color_save_path)
            plt.imsave(osp.join(color_save_path, image_name), colorEstDisp, cmap=plt.cm.hot)

        if 'GroupColor' in result.keys():
            group_save_path = os.path.join(out_dir, 'group_disp')
            mkdir_or_exist(group_save_path)
            plt.imsave(osp.join(group_save_path, image_name), result['GroupColor'], cmap=plt.cm.hot)

        if 'ColorConfidence' in result.keys():
            conf_save_path = os.path.join(out_dir, 'confidence')
            mkdir_or_exist(conf_save_path)
            plt.imsave(osp.join(conf_save_path, image_name), result['ColorConfidence']) 
Example #10
Source File: save_result.py    From DenseMatchingBenchmark with MIT License 6 votes vote down vote up
def __call__(self, result, out_dir, image_name):
        result_tool = ShowResultTool()
        result = result_tool(result)
        if 'GrayDisparity' in result.keys():
            grayEstDisp = result['GrayDisparity']
            gray_save_path = osp.join(out_dir, 'flow_0')
            mkdir_or_exist(gray_save_path)
            skimage.io.imsave(osp.join(gray_save_path, image_name), (grayEstDisp * 256).astype('uint16'))

        if 'ColorDisparity' in result.keys():
            colorEstDisp = result['ColorDisparity']
            color_save_path = osp.join(out_dir, 'color_disp')
            mkdir_or_exist(color_save_path)
            plt.imsave(osp.join(color_save_path, image_name), colorEstDisp, cmap=plt.cm.hot)

        if 'GroupColor' in result.keys():
            group_save_path = os.path.join(out_dir, 'group_flow')
            mkdir_or_exist(group_save_path)
            plt.imsave(osp.join(group_save_path, image_name), result['GroupColor'], cmap=plt.cm.hot) 
Example #11
Source File: test_io.py    From snn_toolbox with MIT License 6 votes vote down vote up
def test_get_dataset_from_png(self, _config):
        try:
            import matplotlib.pyplot as plt
        except ImportError:
            return

        datapath = _config.get('paths', 'dataset_path')
        classpath = os.path.join(datapath, 'class_0')
        os.mkdir(classpath)
        data = np.random.random_sample((10, 10, 3))
        plt.imsave(os.path.join(classpath, 'image_0.png'), data)

        _config.read_dict({
             'input': {'dataset_format': 'png',
                       'dataflow_kwargs': "{'target_size': (11, 12)}",
                       'datagen_kwargs': "{'rescale': 0.003922,"
                                         " 'featurewise_center': True,"
                                         " 'featurewise_std_normalization':"
                                         " True}"}})

        normset, testset = get_dataset(_config)
        assert all([normset, testset]) 
Example #12
Source File: saliency_detection.py    From aitom with GNU General Public License v3.0 6 votes vote down vote up
def gabor_feature_single_job(a, filters, fm_i, label, cluster_center_number, save_flag):
    # convolution
    start_time = time.time()
    # b=SN.correlate(a,filters[i]) # too slow
    b = signal.correlate(a, filters[fm_i], mode='same')
    end_time = time.time()
    print('feature %d done (%f s)' % (fm_i, end_time - start_time))

    # show Gabor filter output
    if save_flag:
        img = (b[:, :, int(a.shape[2] / 2)]).copy()
        plt.imsave('./result/gabor_output(%d).png' % fm_i, img, cmap='gray')  # save fig

    # generate feature vector
    start_time = time.time()
    result = generate_feature_vector(b=b, label=label, cluster_center_number=cluster_center_number)
    end_time = time.time()
    print('feature vector %d done (%f s)' % (fm_i, end_time - start_time))
    return fm_i, result 
Example #13
Source File: wishart.py    From SAR-change-detection with MIT License 6 votes vote down vote up
def wishart_test(mode, ENL, percent):
    # Test statistic over the whole area
    w = Wishart(april, may, ENL, ENL, mode)

    # Test statistic over the no change region
    wno = Wishart(april.region(region_nochange), may.region(region_nochange), ENL, ENL, mode)

    # Histogram, no change region
    f, ax = wno.histogram(percent)
    hist_filename = "fig/wishart/{}/lnq.hist.ENL{}.pdf".format(mode, ENL)
    f.savefig(hist_filename, bbox_inches='tight')

    # Histogram, entire region
    f, ax = w.histogram(percent)
    hist_filename = "fig/wishart/{}/lnq.hist.total.ENL{}.pdf".format(mode, ENL)
    f.savefig(hist_filename, bbox_inches='tight')

    # Binary image
    im = w.image_binary(percent)
    plt.imsave("fig/wishart/{}/lnq.ENL{}.{}.jpg".format(mode, ENL, percent), im, cmap="gray") 
Example #14
Source File: video.py    From phd with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def add_image(self, image):
        """
        Saves image to file.

        Args:
            image (HxWx3).

        Returns:
            str: filename.
        """
        if self.temp_dir is None:
            self.temp_dir = tempfile.mkdtemp()
        if self.img_shape is None:
            self.img_shape = image.shape
        assert self.img_shape == image.shape
        filename = self.get_filename(self.current_index)
        plt.imsave(fname=filename, arr=image)
        self.current_index += 1
        return filename 
Example #15
Source File: unet_trainer.py    From luna16 with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #16
Source File: test_image.py    From neural-network-animation with MIT License 6 votes vote down vote up
def test_imsave_color_alpha():
    # Test that imsave accept arrays with ndim=3 where the third dimension is
    # color and alpha without raising any exceptions, and that the data is
    # acceptably preserved through a save/read roundtrip.
    from numpy import random
    random.seed(1)
    data = random.rand(256, 128, 4)

    buff = io.BytesIO()
    plt.imsave(buff, data)

    buff.seek(0)
    arr_buf = plt.imread(buff)

    # Recreate the float -> uint8 -> float32 conversion of the data
    data = (255*data).astype('uint8').astype('float32')/255
    # Wherever alpha values were rounded down to 0, the rgb values all get set
    # to 0 during imsave (this is reasonable behaviour).
    # Recreate that here:
    for j in range(3):
        data[data[:, :, 3] == 0, j] = 1

    assert_array_equal(data, arr_buf) 
Example #17
Source File: utils.py    From ALOCC-CVPR2018 with MIT License 5 votes vote down vote up
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`.
    """
    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 
Example #18
Source File: event_log.py    From cartpoleplusplus with MIT License 5 votes vote down vote up
def rgb_to_png(rgb):
  """convert RGB data from render to png"""
  sio = StringIO.StringIO()
  plt.imsave(sio, rgb)
  return sio.getvalue() 
Example #19
Source File: calculate_fid.py    From DeepPrivacy with MIT License 5 votes vote down vote up
def save_im(fp, im):
    plt.imsave(fp, im) 
Example #20
Source File: util.py    From cartpoleplusplus with MIT License 5 votes vote down vote up
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 
Example #21
Source File: utils.py    From ALOCC-CVPR2018 with MIT License 5 votes vote down vote up
def save_images(images, size, image_path):
  return imsave(inverse_transform(images), size, image_path) 
Example #22
Source File: cli.py    From pychubby with MIT License 5 votes vote down vote up
def generate(self):
        """Define a subsubcommand."""
        operators = [
            perform.command(name=self.name, help=self.doc),
            click.argument("inp_img", type=click.Path(exists=True)),
            click.argument("out_img", type=click.Path(), required=False),
        ]

        operators += [
            click.option("--{}".format(k), default=v, show_default=True) for k, v in self.kwargs.items()
        ]

        def f(*args, **kwargs):
            """Perform an action."""
            inp_img = kwargs.pop("inp_img")
            out_img = kwargs.pop("out_img")

            img = plt.imread(str(inp_img))
            lf = LandmarkFace.estimate(img)
            cls = getattr(pychubby.actions, self.name)
            a = pychubby.actions.Multiple(cls(**kwargs))

            new_lf, df = a.perform(lf)

            if out_img is not None:
                plt.imsave(str(out_img), new_lf[0].img)
            else:
                new_lf.plot(show_landmarks=False, show_numbers=False)

        for op in operators[::-1]:
            f = op(f)

        return f 
Example #23
Source File: utils.py    From ALOCC-CVPR2018 with MIT License 5 votes vote down vote up
def imsave(images, size, path):
  image = np.squeeze(merge(images, size))
  return scipy.misc.imsave(path, image) 
Example #24
Source File: simulator.py    From doom-net-pytorch with MIT License 5 votes vote down vote up
def draw_objects(self, objects):
        view = self.map.copy()
        view[objects[:, 2], objects[:, 1], 0] = 255
        view[objects[:, 2], objects[:, 1], 1] = 0
        view[objects[:, 2], objects[:, 1], 2] = 0
        plt.imsave('map_points.png', np.flip(view, axis=0)) 
Example #25
Source File: common_caffe2.py    From optimized-models with Apache License 2.0 5 votes vote down vote up
def SaveImage(image, filename):
        """save image"""
        if image.shape[0] != 1:
            logging.error("the shape[0] of the image is not 1")
            return
        img = np.squeeze(image)
        # switch to HWC
        img = img.swapaxes(0, 1).swapaxes(1, 2)
        # switch to RGB
        #img = img[:, :, (2, 1, 0)]
        from matplotlib import pyplot
        pyplot.imsave(filename, img) 
Example #26
Source File: visualization.py    From DeepTL-Lane-Change-Classification with MIT License 5 votes vote down vote up
def visualize_activation_with_image(self, image_path, filter_id=0, layer_name='activation_49', save_option=0, save_path='default'):
        self.activation_model = Model(inputs=self.model.input, outputs=self.model.get_layer(layer_name).output)
        img = image.load_img(image_path, target_size=(224, 224))
        x = image.img_to_array(img)
        x = np.expand_dims(x, axis=0)
        x = preprocess_input(x)

        activation_output = self.activation_model.predict(x)
        ax = plt.subplot(111)
        ax.axis('off')

        if save_option == 1:
            plt.imsave(save_path, activation_output[0, :, :, filter_id])
        elif save_option == 0:
            ax.imshow(activation_output[0, :, :, filter_id]) 
Example #27
Source File: SCVNet.py    From SCVNet with MIT License 5 votes vote down vote up
def saveImage(file, img):
	img = img * 0.5 + 0.5
	npImage = img.numpy()
	plt.imsave(file, np.transpose(npImage, (1, 2, 0)))
	return 
Example #28
Source File: predictor.py    From densemapnet with MIT License 5 votes vote down vote up
def predict_images(self, image, filepath):
        size = [image.shape[0], image.shape[1]]
        if self.settings.otanh:
            image += 1.0
            image =  np.clip(image, 0.0, 2.0)
            image *= (255*0.5)
        else:
            image =  np.clip(image, 0.0, 1.0)
            image *= 255

        image = image.astype(np.uint8)
        image = np.reshape(image, size)
        misc.imsave(filepath, image) 
Example #29
Source File: test.py    From vess2ret with MIT License 5 votes vote down vote up
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) 
Example #30
Source File: tf_process.py    From Super-Resolution_CNN with MIT License 5 votes vote down vote up
def validation(sess, neuralnet, saver, dataset):

    if(os.path.exists(PACK_PATH+"/Checkpoint/model_checker.index")):
        saver.restore(sess, PACK_PATH+"/Checkpoint/model_checker")

    makedir(PACK_PATH+"/test")
    makedir(PACK_PATH+"/test/reconstruction")

    start_time = time.time()
    print("\nValidation")
    for tidx in range(dataset.amount_te):

        X_te, Y_te = dataset.next_test()
        if(X_te is None): break

        img_recon, tmp_psnr = sess.run([neuralnet.recon, neuralnet.psnr], feed_dict={neuralnet.inputs:X_te, neuralnet.outputs:Y_te})
        img_recon = np.squeeze(img_recon, axis=0)
        plt.imsave("%s/test/reconstruction/%09d_psnr_%d.png" %(PACK_PATH, tidx, int(tmp_psnr)), img_recon)

        img_input = np.squeeze(X_te, axis=0)
        img_ground = np.squeeze(Y_te, axis=0)
        plt.imsave("%s/test/bicubic.png" %(PACK_PATH), img_input)
        plt.imsave("%s/test/high-resolution.png" %(PACK_PATH), img_ground)

    elapsed_time = time.time() - start_time
    print("Elapsed: "+str(elapsed_time))