Takes a :py:mod:`PIL.Image` and renders it to the current terminal as
        ASCII-blocks.
353167
def display(self, image):
        
        assert(image.size == self.size)
        self._last_image = image

        surface = self.to_surface(self.preprocess(image), alpha=self._contrast)
        rawbytes = self._pygame.image.tostring(surface, "RGB", False)
        image = Image.frombytes("RGB", surface.get_size(), rawbytes)

        scr_width = self._terminal_size()[1]
        scale = float(scr_width) / image.width

        self._CSI('1;1H')  # Move to top/left

        for (fg, bg) in self._generate_art(image, int(image.width * scale), int(image.height * scale)):
            self._CSI('38;5;{0};48;5;{1}m'.format(fg, bg))
            sys.stdout.write('▄')

        self._CSI('0m')
        sys.stdout.flush()
658702
def imagemagick(color_count, img, magick_command):
    """"""
    flags = ["-resize", "25%", "-colors", str(color_count),
             "-unique-colors", "txt:-"]
    img += "[0]"

    return subprocess.check_output([*magick_command, img, *flags]).splitlines()
56356
def topng(images, path, prefix="image", overwrite=False, credentials=None):
    
    value_shape = images.value_shape
    if not len(value_shape) in [2, 3]:
        raise ValueError("Only 2D or 3D images can be exported to png, "
                         "images are %d-dimensional." % len(value_shape))

    from scipy.misc import imsave
    from io import BytesIO
    from thunder.writers import get_parallel_writer

    def tobuffer(kv):
        key, img = kv
        fname = prefix+"-"+"%05d.png" % int(key)
        bytebuf = BytesIO()
        imsave(bytebuf, img, format='PNG')
        return fname, bytebuf.getvalue()

    writer = get_parallel_writer(path)(path, overwrite=overwrite, credentials=credentials)
    images.foreach(lambda x: writer.write(tobuffer(x)))
1005062
def open_image(fn:PathOrStr, div:bool=True, convert_mode:str='RGB', cls:type=Image,
        after_open:Callable=None)->Image:
    ""
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", UserWarning) # EXIF warning from TiffPlugin
        x = PIL.Image.open(fn).convert(convert_mode)
    if after_open: x = after_open(x)
    x = pil2tensor(x,np.float32)
    if div: x.div_(255)
    return cls(x)
526021
def plot(config, image, file):
    
    image = np.squeeze(image)
    print(file, image.shape)
    imsave(file, image)
285892
def write(self, chars, output, format='png'):
        
        im = self.generate_image(chars)
        return im.save(output, format=format)
397583
def resolve_image_as_pil(self, image_url, coords=None):
        
        files = self.mets.find_files(url=image_url)
        if files:
            image_filename = self.download_file(files[0]).local_filename
        else:
            image_filename = self.download_url(image_url)

        if image_url not in self.image_cache['pil']:
            self.image_cache['pil'][image_url] = Image.open(image_filename)

        pil_image = self.image_cache['pil'][image_url]

        if coords is None:
            return pil_image
        if image_url not in self.image_cache['cv2']:
            log.debug("Converting PIL to OpenCV: %s", image_url)
            color_conversion = cv2.COLOR_GRAY2BGR if pil_image.mode in ('1', 'L') else  cv2.COLOR_RGB2BGR
            pil_as_np_array = np.array(pil_image).astype('uint8') if pil_image.mode == '1' else np.array(pil_image)
            self.image_cache['cv2'][image_url] = cv2.cvtColor(pil_as_np_array, color_conversion)
        cv2_image = self.image_cache['cv2'][image_url]
        poly = np.array(coords, np.int32)
        log.debug("Cutting region %s from %s", coords, image_url)
        region_cut = cv2_image[
            np.min(poly[:, 1]):np.max(poly[:, 1]),
            np.min(poly[:, 0]):np.max(poly[:, 0])
        ]
        return Image.fromarray(region_cut)
833010
def display(self, image):
        
        assert(image.size == self.size)
        self._last_image = image

        self._count += 1
        filename = self._file_template.format(self._count)
        image = self.preprocess(image)
        surface = self.to_surface(image, alpha=self._contrast)
        logger.debug("Writing: {0}".format(filename))
        self._pygame.image.save(surface, filename)
469609
def post_process(self):
        
        self.image.putdata(self.pixels)
        self.image = self.image.transpose(Image.ROTATE_90)
308851
def render_image_iterm2
      return nil unless valid?

      # References:
      # https://iterm2.com/documentation-images.html
      # https://iterm2.com/utilities/imgcat

      # tmux requires some extra work for unrecognised escape code sequences
      screen = ENV['TERM'].start_with? 'screen'
      prefix = screen ? "\ePtmux;\e\e]" : "\e]"
      suffix = screen ? "\a\e\\" : "\a"

      png = qrcode.as_png(size: 600)
      png_base64 = Base64.encode64(png.to_s).chomp
      options = 'inline=1'
      "#{prefix}1337;File=#{options}:#{png_base64}#{suffix}"
    end
1276239
def get_buffer(self, data_np, header, format, output=None):
        
        if not have_pil:
            raise Exception("Install PIL to use this method")
        image = PILimage.fromarray(data_np)
        buf = output
        if buf is None:
            buf = BytesIO()
        image.save(buf, format)
        return buf
1018280
def _print_image(self, line, size):
        
        i = 0
        cont = 0
        buffer = ""

       
        self._raw(S_RASTER_N)
        buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1], 0)
        self._raw(buffer.decode('hex'))
        buffer = ""

        while i < len(line):
            hex_string = int(line[i:i+8],2)
            buffer += "%02X" % hex_string
            i += 8
            cont += 1
            if cont % 4 == 0:
                self._raw(buffer.decode("hex"))
                buffer = ""
                cont = 0
653480
def plaintext(self, result):
        
        from PIL import Image

        ascii_chars = ['#', 'A', '@', '%', 'S', '+', '<', '*', ':', ',', '.']

        def image_to_ascii(image):
            image_as_ascii = []
            all_pixels = list(image.getdata())
            for pixel_value in all_pixels:
                index = pixel_value / 25 # 0 - 10
                image_as_ascii.append(ascii_chars[index])
            return image_as_ascii   

        img = Image.open(result)
        width, heigth = img.size
        new_width = 80 
        new_heigth = int((heigth * new_width) / width)
        new_image = img.resize((new_width, new_heigth))
        new_image = new_image.convert("L") # convert to grayscale

        # now that we have a grayscale image with some fixed width we have to convert every pixel
        # to the appropriate ascii character from "ascii_chars"
        img_as_ascii = image_to_ascii(new_image)
        img_as_ascii = ''.join(ch for ch in img_as_ascii)
        out = []
        for c in range(0, len(img_as_ascii), new_width):
            out.append(img_as_ascii[c:c+new_width])

        return "\n".join(out)
678319
def as_pil_image(self):
        
        from PIL import Image

        try:
            bio = BytesIO()
            self._extract_direct(stream=bio)
            bio.seek(0)
            return Image.open(bio)
        except UnsupportedImageTypeError:
            pass

        im = self._extract_transcoded()
        if not im:
            raise UnsupportedImageTypeError(repr(self))

        return im
944710
def pil_image3d(input, size=(800, 600), pcb_rotate=(0, 0, 0), timeout=20, showgui=False):
    '''
    
    '''
    f = tempfile.NamedTemporaryFile(suffix='.png', prefix='eagexp_')
    output = f.name

    export_image3d(input, output=output, size=size,
                   pcb_rotate=pcb_rotate, timeout=timeout, showgui=showgui)

    im = Image.open(output)
    return im
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
1131111
def frompil(self, pillow_image):
        """"""
        bio = BytesIO()
        pillow_image.save(bio, format='png', compress_level=1)
        py_buffer = bio.getbuffer()
        c_buffer = ffi.from_buffer(py_buffer)
        with _LeptonicaErrorTrap():
            pix = Pix(lept.pixReadMem(c_buffer, len(c_buffer)))
            return pix