Python png.Writer() Examples

The following are 30 code examples of png.Writer(). 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 png , or try the search function .
Example #1
Source File: io.py    From PyAbel with MIT License 7 votes vote down vote up
def save16bitPNG(filename, data):
    """
    It's not easy to save 16-bit images in Python.
    Here is a way to save a 16-bit PNG
    Again, this is thanks to stackoverflow:
    https://stackoverflow.com/questions/25696615/\
    can-i-save-a-numpy-array-as-a-16-bit-image-using-normal-enthought-python
    This requires pyPNG
    """

    import png
    with open(filename, 'wb') as f:
        writer = png.Writer(width=data.shape[1], height=data.shape[0],
                            bitdepth=16, greyscale=True)
        data_list = data.tolist()
        writer.write(f, data_list) 
Example #2
Source File: vtparse.py    From glasstty with The Unlicense 6 votes vote down vote up
def writepng(self):
        # pack
        s=[]
        i = 0
        b = 0
        for c in self.m:
            i = i + 1
            b = b | (int(c)<<(9-((i-1)%7)))
            if i % 7 == 0: 
                b = b | (b>>1)
                s.append(tobin(~b,10))
                s.append(tobin(~0,10))
                b = 0
        s = map(lambda x: map(int, x), s)
        
        f = open('u%04x.png'%self.charcode, 'wb')
        w = png.Writer(len(s[0]), len(s), greyscale=True, bitdepth=1)
        w.write(f, s)
        f.close() 
Example #3
Source File: stream_server.py    From elijah-provisioning with Apache License 2.0 6 votes vote down vote up
def __init__(self, handoff_url, message_queue, disk_size, mem_size):
        self.url = handoff_url
        self.mq = message_queue
        self.viz_interval = 1 #1000 msecs
        self.disk_chunks = disk_size / 4096
        self.mem_chunks = mem_size / 4096
        self.time_start = self.last_update =  time.time()
        self.num_blobs = 0
        self.disk_applied = 0
        self.mem_applied = 0
        self.iter = 0
        self.outfd = open(name='/var/tmp/cloudlet/handoff_from_%s_at_%d.log' % (self.url, self.time_start), mode = 'w')
        self.stats_path = '/var/www/html/heatmap/stats.txt'

        self.disk_path = '/var/www/html/heatmap/disk.png'
        self.disk_width, self.disk_height = self.layout(self.disk_chunks)
        self.disk_img_data = [[0 for _ in range(self.disk_width)] for _ in range(self.disk_height)]
        self.disk_writer = png.Writer(self.disk_width, self.disk_height, greyscale=True)

        self.mem_path = '/var/www/html/heatmap/mem.png'
        self.mem_width, self.mem_height = self.layout(self.mem_chunks)
        self.mem_img_data = [[0 for _ in range(self.mem_width)] for _ in range(self.mem_height)]
        self.mem_writer = png.Writer(self.mem_width, self.mem_height, greyscale=True)
        multiprocessing.Process.__init__(self, target=self.read_queue) 
Example #4
Source File: convert_mnist_to_png.py    From mnist_png with GNU General Public License v2.0 6 votes vote down vote up
def write_dataset(labels, data, size, rows, cols, output_dir):
    # create output directories
    output_dirs = [
        path.join(output_dir, str(i))
        for i in range(10)
    ]
    for dir in output_dirs:
        if not path.exists(dir):
            os.makedirs(dir)

    # write data
    for (i, label) in enumerate(labels):
        output_filename = path.join(output_dirs[label], str(i) + ".png")
        print("writing " + output_filename)
        with open(output_filename, "wb") as h:
            w = png.Writer(cols, rows, greyscale=True)
            data_i = [
                data[ (i*rows*cols + j*cols) : (i*rows*cols + (j+1)*cols) ]
                for j in range(rows)
            ]
            w.write(h, data_i) 
Example #5
Source File: BopWriter.py    From BlenderProc with GNU General Public License v3.0 6 votes vote down vote up
def save_depth(path, im):
    """Saves a depth image (16-bit) to a PNG file.
    From the BOP toolkit (https://github.com/thodan/bop_toolkit).

    :param path: Path to the output depth image file.
    :param im: ndarray with the depth image to save.
    """
    if not path.endswith(".png"):
        raise ValueError('Only PNG format is currently supported.')

    im[im > 65535] = 65535
    im_uint16 = np.round(im).astype(np.uint16)

    # PyPNG library can save 16-bit PNG and is faster than imageio.imwrite().
    w_depth = png.Writer(im.shape[1], im.shape[0], greyscale=True, bitdepth=16)
    with open(path, 'wb') as f:
        w_depth.write(f, np.reshape(im_uint16, (-1, im.shape[1]))) 
Example #6
Source File: convert.py    From tzxtools with GNU General Public License v3.0 6 votes vote down vote up
def convertToScreen(data, out, org=0):
    pixel = []
    for y in range(192):
        pixrow = []
        pixel.append(pixrow)
        for col in range(32):
            palette = readColor(data, y, col)
            bits = readBits(data, y, col)
            for b in range(8):
                if bits & (0b10000000 >> b):
                    pixrow.append(palette[0])
                else:
                    pixrow.append(palette[1])

    import png
    pngw = png.Writer(256, 192, palette=PALETTE)
    pngw.write(out, pixel) 
Example #7
Source File: depth_map_utils.py    From monopsr with MIT License 5 votes vote down vote up
def save_depth_map(save_path, depth_map,
                   version='cv2', png_compression=3):
    """Saves depth map to disk as uint16 png

    Args:
        save_path: path to save depth map
        depth_map: depth map numpy array [h w]
        version: 'cv2' or 'pypng'
        png_compression: Only when version is 'cv2', sets png compression level.
            A lower value is faster with larger output,
            a higher value is slower with smaller output.
    """

    # Convert depth map to a uint16 png
    depth_image = (depth_map * 256.0).astype(np.uint16)

    if version == 'cv2':
        cv2.imwrite(save_path, depth_image, [cv2.IMWRITE_PNG_COMPRESSION, png_compression])

    elif version == 'pypng':
        with open(save_path, 'wb') as f:
            depth_image = (depth_map * 256.0).astype(np.uint16)
            writer = png.Writer(width=depth_image.shape[1],
                                height=depth_image.shape[0],
                                bitdepth=16,
                                greyscale=True)
            writer.write(f, depth_image)

    else:
        raise ValueError('Invalid version', version) 
Example #8
Source File: inout.py    From patch_linemod with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save_depth(path, im):
    # PyPNG library is used since it allows to save 16-bit PNG
    w_depth = png.Writer(im.shape[1], im.shape[0], greyscale=True, bitdepth=16)
    im_uint16 = np.round(im).astype(np.uint16)
    with open(path, 'wb') as f:
        w_depth.write(f, np.reshape(im_uint16, (-1, im.shape[1]))) 
Example #9
Source File: test-coco.py    From DSRG with MIT License 5 votes vote down vote up
def write_to_png_file(im, f):
    #global palette
    #palette_int = map(lambda x: map(lambda xx: int(255 * xx), x), palette)
    #w = png.Writer(size=(im.shape[1], im.shape[0]), bitdepth=8, palette=palette_int)
    #with open(f, "w") as ff:
    #    w.write(ff, im)
    cv2.imwrite(f, im) 
Example #10
Source File: generate_train_gt.py    From DSRG with MIT License 5 votes vote down vote up
def write_to_png_file(im, f):
    #global palette
    #palette_int = map(lambda x: map(lambda xx: int(255 * xx), x), palette)
    #w = png.Writer(size=(im.shape[1], im.shape[0]), bitdepth=8, palette=palette_int)
    #with open(f, "w") as ff:
    #    w.write(ff, im)
    cv2.imwrite(f, im) 
Example #11
Source File: test-coco-f.py    From DSRG with MIT License 5 votes vote down vote up
def write_to_png_file(im, f):
    #global palette
    #palette_int = map(lambda x: map(lambda xx: int(255 * xx), x), palette)
    #w = png.Writer(size=(im.shape[1], im.shape[0]), bitdepth=8, palette=palette_int)
    #with open(f, "w") as ff:
    #    w.write(ff, im)
    cv2.imwrite(f, im)


# def preprocess(image, size, mean_pixel=mean_pixel):

#     image = np.array(image)
#     # image = nd.zoom(image.astype('float32'),
#     #                 (size / float(image.shape[0]),
#     #                 size / float(image.shape[1]), 1.0),
#     #                 order=1)
#     factor = min(float(size)/image.shape[0], float(size)/image.shape[1])
#     image = cv2.resize(image, None, fx=factor, fy=factor, interpolation=cv2.INTER_LINEAR)
#     shape = image.shape

#     # image = image[:, :, [2, 1, 0]]
#     image = image - mean_pixel
#     img_h, img_w, _ = image.shape
#     pad_h = max(size - img_h, 0)
#     pad_w = max(size - img_w, 0)
#     if pad_h > 0 or pad_w > 0:
#         img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0, 
#             pad_w, cv2.BORDER_CONSTANT, 
#             value=(0.0,0.0,0.0))
#     else:
#         img_pad = image

#     img_h, img_w, _ = img_pad.shape
    
#     h_off = (img_h - size) / 2
#     w_off = (img_w - size) / 2
#     image = np.asarray(img_pad[h_off : h_off+size, w_off : w_off+size], np.float32)

#     image = image.transpose([2, 0, 1])
#     return np.expand_dims(image, 0), shape 
Example #12
Source File: test.py    From DSRG with MIT License 5 votes vote down vote up
def write_to_png_file(im, f):
    #global palette
    #palette_int = map(lambda x: map(lambda xx: int(255 * xx), x), palette)
    #w = png.Writer(size=(im.shape[1], im.shape[0]), bitdepth=8, palette=palette_int)
    #with open(f, "w") as ff:
    #    w.write(ff, im)
    cv2.imwrite(f, im) 
Example #13
Source File: test-ms-f.py    From DSRG with MIT License 5 votes vote down vote up
def write_to_png_file(im, f):
    #global palette
    #palette_int = map(lambda x: map(lambda xx: int(255 * xx), x), palette)
    #w = png.Writer(size=(im.shape[1], im.shape[0]), bitdepth=8, palette=palette_int)
    #with open(f, "w") as ff:
    #    w.write(ff, im)
    cv2.imwrite(f, im)


# def preprocess(image, size, mean_pixel=mean_pixel):

#     image = np.array(image)
#     # image = nd.zoom(image.astype('float32'),
#     #                 (size / float(image.shape[0]),
#     #                 size / float(image.shape[1]), 1.0),
#     #                 order=1)
#     factor = min(float(size)/image.shape[0], float(size)/image.shape[1])
#     image = cv2.resize(image, None, fx=factor, fy=factor, interpolation=cv2.INTER_LINEAR)
#     shape = image.shape

#     # image = image[:, :, [2, 1, 0]]
#     image = image - mean_pixel
#     img_h, img_w, _ = image.shape
#     pad_h = max(size - img_h, 0)
#     pad_w = max(size - img_w, 0)
#     if pad_h > 0 or pad_w > 0:
#         img_pad = cv2.copyMakeBorder(image, 0, pad_h, 0, 
#             pad_w, cv2.BORDER_CONSTANT, 
#             value=(0.0,0.0,0.0))
#     else:
#         img_pad = image

#     img_h, img_w, _ = img_pad.shape
    
#     h_off = (img_h - size) / 2
#     w_off = (img_w - size) / 2
#     image = np.asarray(img_pad[h_off : h_off+size, w_off : w_off+size], np.float32)

#     image = image.transpose([2, 0, 1])
#     return np.expand_dims(image, 0), shape 
Example #14
Source File: show-result.py    From DSRG with MIT License 5 votes vote down vote up
def write_to_png_file(im, f):
    global palette
    palette_int = map(lambda x: map(lambda xx: int(255 * xx), x), palette)
    w = png.Writer(size=(im.shape[1], im.shape[0]), bitdepth=8, palette=palette_int)
    with open(f, "w") as ff:
       w.write(ff, im)
    # cv2.imwrite(f, im) 
Example #15
Source File: summary.py    From stanza-old with Apache License 2.0 5 votes vote down vote up
def log_image(self, step, tag, val):
        '''
        Write an image event.

        :param int step: Time step (x-axis in TensorBoard graphs)
        :param str tag: Label for this value
        :param numpy.ndarray val: Image in RGB format with values from
            0 to 255; a 3-D array with index order (row, column, channel).
            `val.shape[-1] == 3`
        '''
        # TODO: support floating-point tensors, 4-D tensors, grayscale
        if len(val.shape) != 3:
            raise ValueError('`log_image` value should be a 3-D tensor, instead got shape %s' %
                             (val.shape,))
        if val.shape[2] != 3:
            raise ValueError('Last dimension of `log_image` value should be 3 (RGB), '
                             'instead got shape %s' %
                             (val.shape,))
        fakefile = StringIO()
        png.Writer(size=(val.shape[1], val.shape[0])).write(
            fakefile, val.reshape(val.shape[0], val.shape[1] * val.shape[2]))
        encoded = fakefile.getvalue()
        # https://tensorflow.googlesource.com/tensorflow/+/master/tensorflow/core/framework/summary.proto
        RGB = 3
        image = Summary.Image(height=val.shape[0], width=val.shape[1],
                              colorspace=RGB, encoded_image_string=encoded)
        summary = Summary(value=[Summary.Value(tag=tag, image=image)])
        self._add_event(step, summary) 
Example #16
Source File: test_flownet_2015.py    From DF-Net with MIT License 5 votes vote down vote up
def write_flow_png(name, flow):
    H, W, _ = flow.shape
    out = np.ones((H, W, 3), dtype=np.uint64)
    out[:,:,1] = np.minimum(np.maximum(flow[:,:,1]*64.+2**15, 0), 2**16).astype(np.uint64)
    out[:,:,0] = np.minimum(np.maximum(flow[:,:,0]*64.+2**15, 0), 2**16).astype(np.uint64)
    with open(name, 'wb') as f:
        writer = png.Writer(width=W, height=H, bitdepth=16)
        im2list = out.reshape(-1, out.shape[1]*out.shape[2]).tolist()
        writer.write(f, im2list) 
Example #17
Source File: celebA_utils.py    From csgm with MIT License 5 votes vote down vote up
def save_image(image, path):
    """Save an image as a png file"""
    image = dcgan_utils.inverse_transform(image)
    png_writer = png.Writer(64, 64)
    with open(path, 'wb') as outfile:
        png_writer.write(outfile, 255*image.reshape([64,-1])) 
Example #18
Source File: Png.py    From python-in-practice with GNU General Public License v3.0 5 votes vote down vote up
def save(image, filename):
        """save a PNG file"""
        with open(filename, "wb") as file:
            writer = png.Writer(width=image.width, height=image.height,
                    alpha=True)
            writer.write_array(file, list(_rgba_for_pixels(image.pixels))) 
Example #19
Source File: flow.py    From irr with Apache License 2.0 5 votes vote down vote up
def write_flow_png(filename, uv, v=None, mask=None):

    if v is None:
        assert (uv.ndim == 3)
        assert (uv.shape[2] == 2)
        u = uv[:, :, 0]
        v = uv[:, :, 1]
    else:
        u = uv

    assert (u.shape == v.shape)

    height_img, width_img = u.shape
    if mask is None:
        valid_mask = np.ones([height_img, width_img])
    else:
        valid_mask = mask

    flow_u = np.clip((u * 64 + 2 ** 15), 0.0, 65535.0).astype(np.uint16)
    flow_v = np.clip((v * 64 + 2 ** 15), 0.0, 65535.0).astype(np.uint16)
    
    output = np.stack((flow_u, flow_v, valid_mask), axis=-1)

    with open(filename, 'wb') as f:
        writer = png.Writer(width=width_img, height=height_img, bitdepth=16)
        writer.write(f, np.reshape(output, (-1, width_img*3))) 
Example #20
Source File: data_utils.py    From sparse_gen with MIT License 5 votes vote down vote up
def save_mnistomni_image(image, path):
    """Save an image as a png file"""
    png_writer = png.Writer(28, 28, greyscale=True)
    with open(path, 'wb') as outfile:
        png_writer.write(outfile, 255*image)

### CelebA utils 
Example #21
Source File: data_utils.py    From sparse_gen with MIT License 5 votes vote down vote up
def save_celebA_image(image, path):
    """Save an image as a png file"""
    image = inverse_transform(image)
    image = np.maximum(np.minimum(image,1.),0.)
    png_writer = png.Writer(64, 64)
    with open(path, 'wb') as outfile:
        png_writer.write(outfile, 255*image.reshape([64,-1])) 
Example #22
Source File: inout.py    From bop_toolkit with MIT License 5 votes vote down vote up
def save_depth(path, im):
  """Saves a depth image (16-bit) to a PNG file.

  :param path: Path to the output depth image file.
  :param im: ndarray with the depth image to save.
  """
  if path.split('.')[-1].lower() != 'png':
    raise ValueError('Only PNG format is currently supported.')

  im_uint16 = np.round(im).astype(np.uint16)

  # PyPNG library can save 16-bit PNG and is faster than imageio.imwrite().
  w_depth = png.Writer(im.shape[1], im.shape[0], greyscale=True, bitdepth=16)
  with open(path, 'wb') as f:
    w_depth.write(f, np.reshape(im_uint16, (-1, im.shape[1]))) 
Example #23
Source File: server.py    From alpr_utils with GNU General Public License v3.0 5 votes vote down vote up
def png_encode(img):
    height = img.shape[0]
    width = img.shape[1]
    img = img.astype("uint8").reshape((-1, width * 3))
    f = io.BytesIO()
    w = png.Writer(width, height, greyscale=False)
    w.write(f, img.asnumpy())
    return "data:image/png;base64, " + base64.b64encode(f.getvalue()).decode() 
Example #24
Source File: SCVNet.py    From SCVNet with MIT License 5 votes vote down vote up
def savePNG16(file, img):
	with open(file, 'wb') as fileOpened:
		img = img * 256.0
		npImage = img.numpy().astype(np.uint16)
		pngWriter = png.Writer(width=npImage.shape[1], height=npImage.shape[0], bitdepth=16, greyscale=True)
		pngWriter.write(fileOpened, npImage.tolist())

	return 
Example #25
Source File: inout.py    From sixd_toolkit with MIT License 5 votes vote down vote up
def save_im(path, im):
    scipy.misc.imsave(path, im)

    # Using PyPNG (for RGB)
    # w_rgb = png.Writer(im.shape[1], im.shape[0], greyscale=False, bitdepth=8)
    # with open(path, 'wb') as f:
    #     w_rgb.write(f, np.reshape(im, (-1, 3 * im.shape[1]))) 
Example #26
Source File: inout.py    From sixd_toolkit with MIT License 5 votes vote down vote up
def save_depth(path, im):
    # PyPNG library is used since it allows to save 16-bit PNG
    w_depth = png.Writer(im.shape[1], im.shape[0], greyscale=True, bitdepth=16)
    im_uint16 = np.round(im).astype(np.uint16)
    with open(path, 'wb') as f:
        w_depth.write(f, np.reshape(im_uint16, (-1, im.shape[1]))) 
Example #27
Source File: workflow.py    From cartoonify with MIT License 5 votes vote down vote up
def _save_3d_numpy_array_as_png(self, img, path):
        """saves a NxNx3 8 bit numpy array as a png image

        :param img: N.N.3 numpy array
        :param path: path to save image to, e.g. './img/img.png
        :return:
        """
        if len(img.shape) != 3 or img.dtype is not np.dtype('uint8'):
            raise TypeError('image must be NxNx3 array')
        with open(str(path), 'wb') as f:
            writer = png.Writer(img.shape[1], img.shape[0], greyscale=False, bitdepth=8)
            writer.write(f, np.reshape(img, (-1, img.shape[1] * img.shape[2]))) 
Example #28
Source File: inout.py    From patch_linemod with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def save_im(path, im):
    scipy.misc.imsave(path, im)

    # Using PyPNG (for RGB)
    # w_rgb = png.Writer(im.shape[1], im.shape[0], greyscale=False, bitdepth=8)
    # with open(path, 'wb') as f:
    #     w_rgb.write(f, np.reshape(im, (-1, 3 * im.shape[1]))) 
Example #29
Source File: runtestsuite.py    From blenderseed with MIT License 5 votes vote down vote up
def write_rgba_png_file(filepath, rows):
    width = len(rows[0]) / 4
    height = len(rows)
    writer = png.Writer(width=width, height=height, alpha=True)
    with open(filepath, 'wb') as file:
        writer.write(file, rows)


#--------------------------------------------------------------------------------------------------
# Utility class to log progress.
#-------------------------------------------------------------------------------------------------- 
Example #30
Source File: __init__.py    From mritopng with MIT License 5 votes vote down vote up
def mri_to_png(mri_file, png_file, do_auto_contrast=False):
    """ Function to convert from a DICOM image to png

        @param mri_file: An opened file like object to read te dicom data
        @param png_file: An opened file like object to write the png data
    """

    image_2d = extract_grayscale_image(mri_file)

    if do_auto_contrast:
        image_2d = auto_contrast(image_2d)

    # Writing the PNG file
    w = png.Writer(image_2d.width, image_2d.height, greyscale=True)
    w.write(png_file, image_2d.image)