Python imageio.imwrite() Examples

The following are 30 code examples of imageio.imwrite(). 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 imageio , or try the search function .
Example #1
Source File: rendering.py    From 3DDFA with MIT License 6 votes vote down vote up
def obama_demo():
    wd = 'obama_res@dense_py'
    if not osp.exists(wd):
        os.mkdir(wd)

    app = RenderPipeline(**cfg)
    img_fps = sorted(glob('obama/*.jpg'))
    triangles = sio.loadmat('tri_refine.mat')['tri']  # mx3
    triangles = _to_ctype(triangles).astype(np.int32)  # for type compatible

    for img_fp in img_fps[:]:
        vertices = sio.loadmat(img_fp.replace('.jpg', '_0.mat'))['vertex'].T  # mx3
        img = imageio.imread(img_fp).astype(np.float32) / 255.

        # end = time.clock()
        img_render = app(vertices, triangles, img)
        # print('Elapse: {:.1f}ms'.format((time.clock() - end) * 1000))

        img_wfp = osp.join(wd, osp.basename(img_fp))
        imageio.imwrite(img_wfp, img_render)
        print('Writing to {}'.format(img_wfp)) 
Example #2
Source File: utils.py    From training_results_v0.6 with Apache License 2.0 6 votes vote down vote up
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
    """ save image """
    data = data.asnumpy().transpose((0, 2, 3, 1))
    datanp = np.clip(
        (data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
    x_dim = min(8, batch_size)
    y_dim = int(math.ceil(float(batch_size) / x_dim))
    height, width = int(image_size + padding), int(image_size + padding)
    grid = np.zeros((height * y_dim + 1 + padding // 2, width *
                     x_dim + 1 + padding // 2, 3), dtype=np.uint8)
    k = 0
    for y in range(y_dim):
        for x in range(x_dim):
            if k >= batch_size:
                break
            start_y = y * height + 1 + padding // 2
            end_y = start_y + height - padding
            start_x = x * width + 1 + padding // 2
            end_x = start_x + width - padding
            np.copyto(grid[start_y:end_y, start_x:end_x, :], datanp[k])
            k += 1
    imageio.imwrite(
        '{}/fake_samples_epoch_{}.png'.format(output_dir, epoch), grid) 
Example #3
Source File: visual_evaluation.py    From integer_discrete_flows with MIT License 6 votes vote down vote up
def plot_images(args, x_sample, dir, file_name, size_x=10, size_y=10):
    batch, channels, height, width = x_sample.shape

    print(x_sample.shape)

    mosaic = np.zeros((height * size_y, width * size_x, channels))

    for j in range(size_y):
        for i in range(size_x):
            idx = j * size_x + i

            image = x_sample[idx]

            mosaic[j*height:(j+1)*height, i*height:(i+1)*height] = \
                image.transpose(1, 2, 0)

    # Remove channel for BW images
    mosaic = mosaic.squeeze()

    imageio.imwrite(dir + file_name + '.png', mosaic) 
Example #4
Source File: segmentation.py    From segmentation_training_pipeline with MIT License 6 votes vote down vote up
def predict_to_directory(self, spath, tpath,fold=0, stage=0, limit=-1, batchSize=32,binaryArray=False,ttflips=False):
        generic.ensure(tpath)
        with tqdm.tqdm(total=len(generic.dir_list(spath)), unit="files", desc="segmentation of images from " + str(spath) + " to " + str(tpath)) as pbar:
            for v in self.predict_on_directory(spath, fold=fold, stage=stage, limit=limit, batch_size=batchSize, ttflips=ttflips):
                b:imgaug.Batch=v;
                for i in range(len(b.data)):
                    id=b.data[i];
                    orig=b.images[i];
                    map=b.segmentation_maps_aug[i]
                    scaledMap=imgaug.augmenters.Scale({"height": orig.shape[0], "width": orig.shape[1]}).augment_segmentation_maps([map])
                    if isinstance(tpath, datasets.ConstrainedDirectory):
                        tp=tpath.path
                    else:
                        tp=tpath
                    if binaryArray:
                        np.save(os.path.join(tp, id[0:id.index('.')]),scaledMap[0].arr);
                    else: imageio.imwrite(os.path.join(tp, id[0:id.index('.')] + ".png"), (scaledMap[0].arr*255).astype(np.uint8))
                pbar.update(batchSize) 
Example #5
Source File: models.py    From SteganoGAN with MIT License 6 votes vote down vote up
def encode(self, cover, output, text):
        """Encode an image.
        Args:
            cover (str): Path to the image to be used as cover.
            output (str): Path where the generated image will be saved.
            text (str): Message to hide inside the image.
        """
        cover = imread(cover, pilmode='RGB') / 127.5 - 1.0
        cover = torch.FloatTensor(cover).permute(2, 1, 0).unsqueeze(0)

        cover_size = cover.size()
        # _, _, height, width = cover.size()
        payload = self._make_payload(cover_size[3], cover_size[2], self.data_depth, text)

        cover = cover.to(self.device)
        payload = payload.to(self.device)
        generated = self.encoder(cover, payload)[0].clamp(-1.0, 1.0)

        generated = (generated.permute(2, 1, 0).detach().cpu().numpy() + 1.0) * 127.5
        imwrite(output, generated.astype('uint8'))

        if self.verbose:
            print('Encoding completed.') 
Example #6
Source File: models.py    From SteganoGAN with MIT License 6 votes vote down vote up
def _generate_samples(self, samples_path, cover, epoch):
        cover = cover.to(self.device)
        generated, payload, decoded = self._encode_decode(cover)
        samples = generated.size(0)
        for sample in range(samples):
            cover_path = os.path.join(samples_path, '{}.cover.png'.format(sample))
            sample_name = '{}.generated-{:2d}.png'.format(sample, epoch)
            sample_path = os.path.join(samples_path, sample_name)

            image = (cover[sample].permute(1, 2, 0).detach().cpu().numpy() + 1.0) / 2.0
            imageio.imwrite(cover_path, (255.0 * image).astype('uint8'))

            sampled = generated[sample].clamp(-1.0, 1.0).permute(1, 2, 0)
            sampled = sampled.detach().cpu().numpy() + 1.0

            image = sampled / 2.0
            imageio.imwrite(sample_path, (255.0 * image).astype('uint8')) 
Example #7
Source File: ILSVRC2012.py    From Robust-Conditional-GAN with MIT License 6 votes vote down vote up
def save_data_list(input_dir, filepathes):
    """
      Read, resize and save images listed in filepathes.
    """

    cnt = 0
    bad_img = list()
    for filepath in filepathes:
        image_path = os.path.join(input_dir, filepath)
        img, path = common.misc.get_image(image_path, LOAD_SIZE, is_crop=False)
        if img is None:
            bad_img.append(path)
            np.savetxt('../bad_img.txt', bad_img, fmt='%s', comments=None)
            continue
        img = img.astype('uint8')

        output_file = os.path.join(OUTPUT_DIR, filepath)
        if not os.path.exists(os.path.dirname(output_file)):
            os.mkdir(os.path.dirname(output_file))
        imageio.imwrite(output_file, img)

        cnt += 1
        if cnt % 1000 == 0:
            print('Resizing %d / %d' % (cnt, len(filepathes))) 
Example #8
Source File: util_io.py    From AniSeg with Apache License 2.0 6 votes vote down vote up
def imsave(path, img):
  # type: (str, (Union[np.ndarray,list])) -> None
  """
  Automatically clip the image represented in a numpy array to 0~255 and save the image.
  :param path: Path to save the image.
  :param img: Image represented in numpy array with a legal format for scipy.misc.imsave
  :return: None
  """
  if isinstance(img, list):
    img = np.array(img)
  if img.shape[-1] > 3 and len(img.shape) >= 3:
    # Convert the image into one channel by summing all channels together
    img = np.sum(img, axis=-1, keepdims=True)
  img = np.clip(img, 0, 255).astype(np.uint8)
  if len(img.shape) == 3 and img.shape[-1] == 1:
    img = np.squeeze(img, -1)
  imageio.imwrite(path, img) 
Example #9
Source File: test_fastai_image_handler.py    From BentoML with Apache License 2.0 6 votes vote down vote up
def test_fastai_image_input(capsys, tmpdir):
    class ImageInputModelForFastai(bentoml.BentoService):
        @bentoml.api(input=FastaiImageInput())
        def predict(self, image):
            return list(image.shape)

    ms = ImageInputModelForFastai()

    import imageio
    import numpy as np

    img_file = tmpdir.join("img.png")
    imageio.imwrite(str(img_file), np.zeros((10, 10)))
    api = ms.get_service_apis()[0]
    test_args = ["--input={}".format(img_file)]
    api.handle_cli(test_args)
    out, _ = capsys.readouterr()
    assert out.strip() == '[3, 10, 10]' 
Example #10
Source File: inception_score.py    From BigGAN-TPU-TensorFlow with MIT License 6 votes vote down vote up
def test_debug(self):
		image = imageio.imread("./temp/dump.png")
		grid_n = 6
		img_size = image.shape[1] // grid_n
		img_ch = image.shape[-1]

		images = np.vsplit(image, grid_n)
		images = [np.hsplit(i, grid_n) for i in images]
		images = np.reshape(np.array(images), [grid_n*grid_n, img_size, img_size, img_ch])

		with tf.Graph().as_default():
			with tf.Session() as sess:
				v_images_placeholder = tf.placeholder(dtype=tf.float32)
				v_images = tf.contrib.gan.eval.preprocess_image(v_images_placeholder)
				v_logits = tf.contrib.gan.eval.run_inception(v_images)
				v_score = tf.contrib.gan.eval.classifier_score_from_logits(v_logits)
				score, logits = sess.run([v_score, v_logits], feed_dict={v_images_placeholder:images})


		imageio.imwrite("./temp/inception_logits.png", logits) 
Example #11
Source File: utility.py    From EDSR-PyTorch with MIT License 6 votes vote down vote up
def begin_background(self):
        self.queue = Queue()

        def bg_target(queue):
            while True:
                if not queue.empty():
                    filename, tensor = queue.get()
                    if filename is None: break
                    imageio.imwrite(filename, tensor.numpy())
        
        self.process = [
            Process(target=bg_target, args=(self.queue,)) \
            for _ in range(self.n_processes)
        ]
        
        for p in self.process: p.start() 
Example #12
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def begin_background(self):
        self.queue = Queue()

        def bg_target(queue):
            while True:
                if not queue.empty():
                    filename, tensor = queue.get()
                    if filename is None: break
                    imageio.imwrite(filename, tensor.numpy())
        
        self.process = [
            Process(target=bg_target, args=(self.queue,)) \
            for _ in range(self.n_processes)
        ]
        
        for p in self.process: p.start() 
Example #13
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def begin_background(self):
        self.queue = Queue()

        def bg_target(queue):
            while True:
                if not queue.empty():
                    filename, tensor = queue.get()
                    if filename is None: break
                    imageio.imwrite(filename, tensor.numpy())
        
        self.process = [
            Process(target=bg_target, args=(self.queue,)) \
            for _ in range(self.n_processes)
        ]
        
        for p in self.process: p.start() 
Example #14
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def begin_background(self):
        self.queue = Queue()

        def bg_target(queue):
            while True:
                if not queue.empty():
                    filename, tensor = queue.get()
                    if filename is None: break
                    imageio.imwrite(filename, tensor.numpy())
        
        self.process = [
            Process(target=bg_target, args=(self.queue,)) \
            for _ in range(self.n_processes)
        ]
        
        for p in self.process: p.start() 
Example #15
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def begin_background(self):
        self.queue = Queue()

        def bg_target(queue):
            while True:
                if not queue.empty():
                    filename, tensor = queue.get()
                    if filename is None: break
                    imageio.imwrite(filename, tensor.numpy())
        
        self.process = [
            Process(target=bg_target, args=(self.queue,)) \
            for _ in range(self.n_processes)
        ]
        
        for p in self.process: p.start() 
Example #16
Source File: utility.py    From OISR-PyTorch with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def begin_background(self):
        self.queue = Queue()

        def bg_target(queue):
            while True:
                if not queue.empty():
                    filename, tensor = queue.get()
                    if filename is None: break
                    imageio.imwrite(filename, tensor.numpy())
        
        self.process = [
            Process(target=bg_target, args=(self.queue,)) \
            for _ in range(self.n_processes)
        ]
        
        for p in self.process: p.start() 
Example #17
Source File: plotting.py    From pyvista with MIT License 6 votes vote down vote up
def _save_image(image, filename, return_img=None):
        """Save a NumPy image array.

        This is an internal helper.

        """
        if not image.size:
            raise ValueError('Empty image. Have you run plot() first?')
        # write screenshot to file
        supported_formats = [".png", ".jpeg", ".jpg", ".bmp", ".tif", ".tiff"]
        if isinstance(filename, str):
            if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
                filename = os.path.join(pyvista.FIGURE_PATH, filename)
            if not any([filename.lower().endswith(ext) for ext in supported_formats]):
                filename += ".png"
            filename = os.path.abspath(os.path.expanduser(filename))
            w = imageio.imwrite(filename, image)
            if not return_img:
                return w
        return image 
Example #18
Source File: utils.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def save_image(data, epoch, image_size, batch_size, output_dir, padding=2):
    """ save image """
    data = data.asnumpy().transpose((0, 2, 3, 1))
    datanp = np.clip(
        (data - np.min(data))*(255.0/(np.max(data) - np.min(data))), 0, 255).astype(np.uint8)
    x_dim = min(8, batch_size)
    y_dim = int(math.ceil(float(batch_size) / x_dim))
    height, width = int(image_size + padding), int(image_size + padding)
    grid = np.zeros((height * y_dim + 1 + padding // 2, width *
                     x_dim + 1 + padding // 2, 3), dtype=np.uint8)
    k = 0
    for y in range(y_dim):
        for x in range(x_dim):
            if k >= batch_size:
                break
            start_y = y * height + 1 + padding // 2
            end_y = start_y + height - padding
            start_x = x * width + 1 + padding // 2
            end_x = start_x + width - padding
            np.copyto(grid[start_y:end_y, start_x:end_x, :], datanp[k])
            k += 1
    imageio.imwrite(
        '{}/fake_samples_epoch_{}.png'.format(output_dir, epoch), grid) 
Example #19
Source File: render_mesh.py    From DEODR with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def example_channels(display=True, save_image=False, width=640, height=480):
    obj_file = os.path.join(deodr.data_path, "duck.obj")
    scene, camera = default_scene(obj_file, width=width, height=height)

    def normalize(v):
        if v.ndim == 3 and v.shape[2] < 3:
            nv = np.zeros((v.shape[0], v.shape[1], 3))
            nv[:, :, : v.shape[2]] = v
        else:
            nv = v
        return (nv - nv.min()) / (nv.max() - nv.min())

    channels = scene.render_deferred(camera)
    if display:
        plt.figure()
        for i, (name, v) in enumerate(channels.items()):
            ax = plt.subplot(2, 3, i + 1)
            ax.set_title(name)
            ax.imshow(normalize(v))

    if save_image:
        for name, v in channels.items():
            image_file = os.path.abspath(
                os.path.join(deodr.data_path, f"test/duck_{name}.png")
            )
            os.makedirs(os.path.dirname(image_file), exist_ok=True)
            image_uint8 = (normalize(v) * 255).astype(np.uint8)
            imageio.imwrite(image_file, image_uint8) 
Example #20
Source File: cgan.py    From Zeroshot-GAN with MIT License 5 votes vote down vote up
def save_image(self, x, path):
		"""
		Save trained image for each epoch
		"""
		imageio.imwrite(path, x)	
		pass 
Example #21
Source File: test.py    From vnlnet with GNU General Public License v3.0 5 votes vote down vote up
def write_file(f, img):
    """
    Write a file f.
    """
    img = np.squeeze(img)
    if f[-4:] == 'tiff' or f[-3:] == 'tif':
        tifffile.imsave(f, img)
    else:
        img = np.floor(img + 0.5)
        img[img < 0] = 0
        img[img > 255] = 255
        img = np.asarray(img, dtype=np.uint8)
        imageio.imwrite(f, img) 
Example #22
Source File: cgan.py    From Zeroshot-GAN with MIT License 5 votes vote down vote up
def imsave(images, size, path):
    image = np.squeeze(merge(images, size))
    return imageio.imwrite(path, image) 
Example #23
Source File: np_visualizer.py    From pytorch_GAN_zoo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def saveTensor(data, out_size_image, path):

    interpolation = 'nearest'
    if isinstance(out_size_image, tuple):
        out_size_image = out_size_image[0]
    data = torch.clamp(data, min=-1, max=1)
    outdata = make_numpy_grid(
        data.numpy(), imgMinSize=out_size_image, interpolation=interpolation)
    imageio.imwrite(path, outdata) 
Example #24
Source File: datasets.py    From pytorch_GAN_zoo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def saveImage(path, image):
    return imageio.imwrite(path, image) 
Example #25
Source File: preprocess.py    From deep-learning-for-document-dewarping with MIT License 5 votes vote down vote up
def resize_and_rotate(filename):
    img = cv2.imread(filename)[:, :, ::-1]
    print('image opened: ' + filename)
    img = rotate_image(img,90)
    img = ia.imresize_single_image(img, (1024, 2048))

    cv2.imwrite(filename, img)
    print('image rotated and resized saved as: ' + filename) 
Example #26
Source File: preprocess.py    From deep-learning-for-document-dewarping with MIT License 5 votes vote down vote up
def imgaug(args):
    # Number of batches and batch size for this example
    filename, root, fold_A = args
    img = cv2.imread(os.path.join(root,filename))
    print('image opened ' + os.path.join(root,filename))
    batch_size = 4
    for i in range(0,batch_size):
        imageio.imwrite(os.path.join(root, os.path.splitext(filename)[0] + '_' + str(i) + '.jpg'), img) #convert the current image in B into a jpg from png
    nb_batches = 1

    # Example augmentation sequence to run in the background
    sometimes = lambda aug: iaa.Sometimes(0.4, aug)
    augseq = iaa.Sequential(
            [
                iaa.PiecewiseAffine(scale=(0.01, 0.01005))
            ]
        )

    # Make batches out of the example image (here: 10 batches, each 32 times
    # the example image)
    batches = []
    for _ in range(nb_batches):
        batches.append(Batch(images=[img] * batch_size))

    #Save images
    for batch in augseq.augment_batches(batches, background=False):
        count = 0
        for img in batch.images_aug:
            path = os.path.join(fold_A,root.rsplit('/', 1)[-1], os.path.splitext(filename)[0] + '_' + str(count) + '.jpg')
            cv2.imwrite(path, img)
            print('image saved as: ' + path)
            count +=1 
Example #27
Source File: preprocess.py    From deep-learning-for-document-dewarping with MIT License 5 votes vote down vote up
def resize(args):
    img_size,filepath = args
    sq_img = cv2.imread(filepath) # square image
    scaled_sq_img = resizeAndPad(sq_img, (img_size,img_size), 127)
    cv2.imwrite(filepath, scaled_sq_img) 
Example #28
Source File: annotatedphotowriter.py    From deepvisualminer with MIT License 5 votes vote down vote up
def execute(self, input_data, input_directory, output_directory):
        if not input_data['isphoto']:
            return {}
        
        img = input_data['img'].copy()
        
        for comp in self.cfg['inputs']:
            comp_outputs = input_data.get(comp)
            comp_reports = comp_outputs['reports']
            if not comp_reports:
                print("Warning: pipeline file specifies {} as input for {} but {} is not outputting any location reports".format(
                    comp, self.name, comp
                ))
                continue
            
            annotate(img, comp_reports)
        
        # The output directory structure should match input directory structure.
        relpath_of_input_file = os.path.relpath(input_data['file'], input_directory)
        relparent_of_input_file = os.path.dirname(relpath_of_input_file)
        inp_filename,inp_extension = os.path.splitext(os.path.basename(relpath_of_input_file))
        
        output_filedir = os.path.join(output_directory, relparent_of_input_file)
        if not os.path.exists(output_filedir):
            os.makedirs(output_filedir)
            
        output_filepath =  os.path.join(output_filedir,
            inp_filename + '-annotated.' + self.cfg['params']['format'])
        
        if self.cfg['params'].get('size'):
            final_img = cv2.resize(img, (self.cfg['params']['size']['width'], self.cfg['params']['size']['height']))
        else:
            final_img = img
            
        print(output_filepath)
        imageio.imwrite(output_filepath, final_img)
                
        return {'file':output_filepath} 
Example #29
Source File: annotatedframewriter.py    From deepvisualminer with MIT License 5 votes vote down vote up
def execute(self, input_data, input_directory, output_directory):
        if not input_data['isvideo']:
            return {}
        
        img = input_data['img'].copy()
        
        for comp in self.cfg['inputs']:
            comp_outputs = input_data.get(comp)
            comp_reports = comp_outputs['reports']
            if not comp_reports:
                print("Warning: pipeline file specifies {} as input for {} but {} is not outputting any location reports".format(
                    comp, self.name, comp
                ))
                continue
            
            annotate(img, comp_reports)
        
        # The output directory structure should match input directory structure.
        relpath_of_input_file = os.path.relpath(input_data['file'], input_directory)
        relparent_of_input_file = os.path.dirname(relpath_of_input_file)
        inp_filename,inp_extension = os.path.splitext(os.path.basename(relpath_of_input_file))
        
        output_filedir = os.path.join(output_directory, relparent_of_input_file)
        if not os.path.exists(output_filedir):
            os.makedirs(output_filedir)
            
        output_filepath =  os.path.join(output_filedir,
            inp_filename + '-frame-' + str(input_data['frame']) + '-annotated.' + self.cfg['params']['format'])
            
        final_img = cv2.resize(img, (self.cfg['params']['size']['width'], self.cfg['params']['size']['height']))
            
        print(output_filepath)
        imageio.imwrite(output_filepath, final_img)
        
        return {'file':output_filepath} 
Example #30
Source File: utils.py    From BigGAN-TPU-TensorFlow with MIT License 5 votes vote down vote up
def imwrite(file, data):

    # Normalised [0,255] as integer
    d = 255 * (data - np.min(data)) / np.ptp(data)
    d = d.astype(np.uint8)

    imageio.imwrite(file, d, format="png")