Yield images encoded as pngs.
555398
def encode_images_as_png(images):
  """"""
  if tf.executing_eagerly():
    for image in images:
      yield tf.image.encode_png(image).numpy()
  else:
    (height, width, channels) = images[0].shape
    with tf.Graph().as_default():
      image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels))
      encoded_image_t = tf.image.encode_png(image_t)
      with tf.Session() as sess:
        for image in images:
          enc_string = sess.run(encoded_image_t, feed_dict={image_t: image})
          yield enc_string
728712
def get_files_from_textfile(textfile_handler):
    """"""
    for line in textfile_handler:
        line = line.rstrip()
        try:
            (image_name, width) = line.rsplit(',', 1)
            width = int(width)
        except ValueError:
            image_name = line
            width = None
        yield (image_name, width)
736041
function createPng(pixelData) {
	const length = pixelData.length + 4 - (pixelData.length % 4);
	const pixels = Math.ceil(length / 4);
	const width = Math.min(pixels, MAX_WIDTH);
	const height = Math.ceil(pixels / MAX_WIDTH);
	const bytesPerRow = width * 4;
	const buffer$$1 = buffer.Buffer.alloc((bytesPerRow + 1) * height);

	// Write pixel data to buffer
	for (let y = 0; y < height; y += 1) {
		const offset = y * bytesPerRow;
		const rowData = pixelData.slice(offset, offset + bytesPerRow);
		const rowStartX = offset + y + 1;
		const rowEndX = rowStartX + bytesPerRow;

		buffer$$1.writeUInt8(0, offset + y);
		buffer$$1.fill(rowData, rowStartX, rowEndX);
	}

	return new Promise((resolve, reject) => {
		zlib.deflate(buffer$$1, (error, deflated) => {
			if (error) {
				reject(error);
				return;
			}

			resolve(buffer.Buffer.concat([
				PNG_HEADER,
				createIHDRChunk(width, height),
				createIDATChunk(deflated),
				createIENDChunk(),
			]));
		});
	});
}
1100089
def save_as_png(self, filename, width=300, height=250, render_time=1):
        """"""
        self.driver.set_window_size(width, height)
        self.driver.get('file://{path}/{filename}'.format(
            path=os.getcwd(), filename=filename + ".html"))
        time.sleep(render_time)
        self.driver.save_screenshot(filename + ".png")
492942
def rle_encode(img:NPArrayMask)->str:
    ""
    pixels = np.concatenate([[0], img.flatten() , [0]])
    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
    runs[1::2] -= runs[::2]
    return ' '.join(str(x) for x in runs)
36693
def generate(str, alg):
    """"""
    img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
    hashcode = hash_input(str, alg)
    pixelmap = setup_pixelmap(hashcode)
    draw_image(pixelmap, img)
    return img
1331921
def _produce_jbig2_images(jbig2_groups, root, log, options):
    """"""

    def jbig2_group_futures(executor, root, groups):
        for group, xref_exts in groups.items():
            prefix = f'group{group:08d}'
            future = executor.submit(
                jbig2enc.convert_group,
                cwd=fspath(root),
                infiles=(img_name(root, xref, ext) for xref, ext in xref_exts),
                out_prefix=prefix,
            )
            yield future

    def jbig2_single_futures(executor, root, groups):
        for group, xref_exts in groups.items():
            prefix = f'group{group:08d}'
            # Second loop is to ensure multiple images per page are unpacked
            for n, xref_ext in enumerate(xref_exts):
                xref, ext = xref_ext
                future = executor.submit(
                    jbig2enc.convert_single,
                    cwd=fspath(root),
                    infile=img_name(root, xref, ext),
                    outfile=root / f'{prefix}.{n:04d}',
                )
                yield future

    if options.jbig2_page_group_size > 1:
        jbig2_futures = jbig2_group_futures
    else:
        jbig2_futures = jbig2_single_futures

    with concurrent.futures.ThreadPoolExecutor(max_workers=options.jobs) as executor:
        futures = jbig2_futures(executor, root, jbig2_groups)
        for future in concurrent.futures.as_completed(futures):
            proc = future.result()
            log.debug(proc.stderr.decode())
542014
def convert_images_to_pil(self, images, dither, nq=0, images_info=None):
        

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim == 3 and im.shape[2] == 3:
                    im = Image.fromarray(im, 'RGB')
                elif im.ndim == 3 and im.shape[2] == 4:
                    # im = Image.fromarray(im[:,:,:3],'RGB')
                    self.transparency = True
                    im = Image.fromarray(im[:, :, :4], 'RGBA')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA")  # NQ assumes RGBA
                nq_instance = NeuQuant(im, int(nq))  # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nq_instance.palette_image(), colors=255)
                else:
                    im = nq_instance.quantize(im, colors=255)  # Use to quantize the image itself

                self.transparency = True  # since NQ assumes transparency
                if self.transparency:
                    alpha = im.split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)
        else:
            # for index,im in enumerate(images):
            for i in range(len(images)):
                im = images[i].convert('RGB').convert('P', palette=Image.ADAPTIVE, dither=dither, colors=255)
                if self.transparency:
                    alpha = images[i].split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)

        # Done
        return images2
698591
def tiles(self):
        
        images = self.parent.images
        for x, y, gid in [i for i in self.iter_data() if i[2]]:
            yield x, y, images[gid]
254250
def pngout(ext_args):
    """"""
    args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename]
    extern.run_ext(args)
    return _PNG_FORMAT
491399
def _make_sprite_image(images, save_path):
    """"""
    if isinstance(images, np.ndarray):
        images = nd.array(images, dtype=images.dtype, ctx=current_context())
    elif not isinstance(images, (NDArray, np.ndarray)):
        raise TypeError('images must be an MXNet NDArray or numpy.ndarray,'
                        ' while received type {}'.format(str(type(images))))

    assert isinstance(images, NDArray)
    shape = images.shape
    nrow = int(np.ceil(np.sqrt(shape[0])))
    _save_image(
        images, os.path.join(save_path, 'sprite.png'), nrow=nrow, padding=0, square_image=True)
833747
def detect_images_and_galleries(generators):
    """"""
    for generator in generators:
        if isinstance(generator, ArticlesGenerator):
            for article in itertools.chain(generator.articles, generator.translations, generator.drafts):
                detect_image(generator, article)
                detect_gallery(generator, article)
        elif isinstance(generator, PagesGenerator):
            for page in itertools.chain(generator.pages, generator.translations, generator.hidden_pages):
                detect_image(generator, page)
                detect_gallery(generator, page)
34210
def latex2png(snippet, outfile):
    """"""
    pngimage = os.path.join(IMAGEDIR, outfile + '.png')
    environment = os.environ
    environment['openout_any'] = 'a'
    environment['shell_escape_commands'] = \
        "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf,gregorio"
    proc = Popen(
        ["lualatex", '-output-directory=' + IMAGEDIR],
        stdin=PIPE,
        stdout=DEVNULL,
        env=environment
    )
    proc.stdin.write(
        (
            LATEX_DOC % (snippet)
        ).encode("utf-8")
    )
    proc.communicate()
    proc.stdin.close()
    call(["pdfcrop", os.path.join(IMAGEDIR, "texput.pdf")], stdout=DEVNULL)
    call(
        [
            "gs",
            "-sDEVICE=pngalpha",
            "-r144",
            "-sOutputFile=" + pngimage,
            os.path.join(IMAGEDIR, "texput-crop.pdf"),
        ],
        stdout=DEVNULL,
    )
142245
def transform(images, out_dir, fname):
        
        from PIL import Image as PILImage
        base = os.path.join(out_dir, "media", "images")
        width, height = images[0].image.size
        num_images_to_log = len(images)

        if num_images_to_log > Image.MAX_IMAGES:
            logging.warn(
                "The maximum number of images to store per step is %i." % Image.MAX_IMAGES)
            num_images_to_log = Image.MAX_IMAGES

        if width * num_images_to_log > Image.MAX_DIMENSION:
            max_images_by_dimension = Image.MAX_DIMENSION // width
            logging.warn("The maximum total width for all images in a collection is 65500, or {} images, each with a width of {} pixels. Only logging the first {} images.".format(max_images_by_dimension, width, max_images_by_dimension))
            num_images_to_log = max_images_by_dimension

        total_width = width * num_images_to_log
        sprite = PILImage.new(
            mode='RGB',
            size=(total_width, height),
            color=(0, 0, 0))
        for i, image in enumerate(images[:num_images_to_log]):
            location = width * i
            sprite.paste(image.image, (location, 0))
        util.mkdir_exists_ok(base)
        sprite.save(os.path.join(base, fname), transparency=0)
        meta = {"width": width, "height": height,
                "count": num_images_to_log, "_type": "images"}
        # TODO: hacky way to enable image grouping for now
        grouping = images[0].grouping
        if grouping:
            meta["grouping"] = grouping
        captions = Image.captions(images[:num_images_to_log])
        if captions:
            meta["captions"] = captions
        return meta
66160
def _generator_file(self):
        """'"""
        for path in self.paths:
            if os.path.isfile(path):
                if isvalid(path, self.access, self.extensions,
                           minsize=self.minsize):
                    yield os.path.abspath(path)
            elif os.path.isdir(path):
                for root, _, fnames in self._walker(path):
                    yield from self._generator_rebase(fnames, root)
476949
def from_image(cls, img_filename, mipmap=False, **kwargs):
        """"""
        img = pyglet.image.load(img_filename)
        tex = img.get_mipmapped_texture() if mipmap else img.get_texture()
        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)
        return cls(id=tex.id, data=tex, mipmap=mipmap, **kwargs)
516348
def save_images(self, directory=None, axis='z', channel=None, global_norm=True, image_format='PNG'):
    """"""
    if directory is None:
      directory = os.path.join('./saved_images', self.dataset_name, self.layer, str(self.mip), self.bounds.to_filename())

    return save_images(self, directory, axis, channel, global_norm, image_format)