convert_images_to_pil(images, nq=0)

        Convert images to Paletted PIL images, which can then be
        written to a single animaged GIF.
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
728908
def postProcess(self, images_data, new_format, new_size):
    
    if len(images_data) == 1:
      in_bytes = io.BytesIO(images_data[0])
      img = PIL.Image.open(in_bytes)
      if img.mode != "RGB":
        img = img.convert("RGB")

    else:
      # images need to be joined before further processing
      logging.getLogger("Cover").info("Joining %u images..." % (len(images_data)))
      # TODO find a way to do this losslessly for JPEG
      new_img = PIL.Image.new("RGB", self.size)
      assert(is_square(len(images_data)))
      sq = int(math.sqrt(len(images_data)))

      images_data_it = iter(images_data)
      img_sizes = {}
      for x in range(sq):
        for y in range(sq):
          current_image_data = next(images_data_it)
          img_stream = io.BytesIO(current_image_data)
          img = PIL.Image.open(img_stream)
          img_sizes[(x, y)] = img.size
          box = [0, 0]
          if x > 0:
            for px in range(x):
              box[0] += img_sizes[(px, y)][0]
          if y > 0:
            for py in range(y):
              box[1] += img_sizes[(x, py)][1]
          box.extend((box[0] + img.size[0], box[1] + img.size[1]))
          new_img.paste(img, box=tuple(box))
      img = new_img

    out_bytes = io.BytesIO()
    if new_size is not None:
      logging.getLogger("Cover").info("Resizing from %ux%u to %ux%u..." % (self.size[0], self.size[1], new_size, new_size))
      img = img.resize((new_size, new_size), PIL.Image.LANCZOS)
      # apply unsharp filter to remove resize blur (equivalent to (images/graphics)magick -unsharp 1.5x1+0.7+0.02)
      # we don't use PIL.ImageFilter.SHARPEN or PIL.ImageEnhance.Sharpness because we want precise control over
      # parameters
      unsharper = PIL.ImageFilter.UnsharpMask(radius=1.5, percent=70, threshold=5)
      img = img.filter(unsharper)
    if new_format is not None:
      logging.getLogger("Cover").info("Converting to %s..." % (new_format.name.upper()))
      target_format = new_format
    else:
      target_format = self.format
    img.save(out_bytes,
             format=target_format.name,
             quality=90,
             optimize=True)
    return out_bytes.getvalue()
1009945
def get_gif_frames(img):
    
    gif_frames = []
    n = 0
    while img:
        if img.mode != "RGB":
            image = img.convert(mode="RGB")
        else:
            image = img
        gif_frames.append(image)
        n += 1
        try:
            img.seek(n)
        except EOFError:
            break
    return gif_frames
586880
def encoded_image(image, options = {})
      target_format = options[:format] || default_render_format

      unless target_format.in?(Alchemy::Picture.allowed_filetypes)
        raise WrongImageFormatError.new(self, target_format)
      end

      options = {
        flatten: target_format != 'gif' && image_file_format == 'gif'
      }.merge(options)

      encoding_options = []

      if target_format =~ /jpe?g/
        quality = options[:quality] || Config.get(:output_image_jpg_quality)
        encoding_options << "-quality #{quality}"
      end

      if options[:flatten]
        encoding_options << '-flatten'
      end

      convertion_needed = target_format != image_file_format || encoding_options.present?

      if has_convertible_format? && convertion_needed
        image = image.encode(target_format, encoding_options.join(' '))
      end

      image
    end
1089868
def save_plain_image_as_file(self, filepath, format='png', quality=90):
        
        pixbuf = self.get_plain_image_as_pixbuf()
        options, values = [], []
        if format == 'jpeg':
            options.append('quality')
            values.append(str(quality))
        pixbuf.savev(filepath, format, options, values)
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
1179904
def pil_image(source, exif_orientation=True, **options):
    
    # Use a BytesIO wrapper because if the source is an incomplete file like
    # object, PIL may have problems with it. For example, some image types
    # require tell and seek methods that are not present on all storage
    # File objects.
    if not source:
        return
    source = BytesIO(source.read())

    image = Image.open(source)
    # Fully load the image now to catch any problems with the image contents.
    try:
        # An "Image file truncated" exception can occur for some images that
        # are still mostly valid -- we'll swallow the exception.
        image.load()
    except IOError:
        pass
    # Try a second time to catch any other potential exceptions.
    image.load()

    if exif_orientation:
        image = utils.exif_orientation(image)
    return image
1135754
def _convert_image(self, im):
        
        pixels   = []
        pix_line = ""
        im_left  = ""
        im_right = ""
        switch   = 0
        img_size = [ 0, 0 ]


        if im.size[0] > 512:
            print  "WARNING: Image is wider than 512 and could be truncated at print time "
        if im.size[1] > 255:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1 ) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break 
            pix_line += im_right
            img_size[0] += im_border[1]

        return (pix_line, img_size)
155729
public void convertToPixels( HashSet<Point> pix ) {
        Iterator<Point> it = pix.iterator();
        while( it.hasNext() ) {
            Point p = it.next();
            pixels[p.x][p.y] = FOREGROUND;
        }
    }
967248
def convert_image_data_to_pil(psd, apply_icc=True, **kwargs):
    
    from PIL import Image, ImageOps
    header = psd.header
    size = (header.width, header.height)
    channels = []
    for channel_data in psd.image_data.get_data(header):
        channels.append(_create_channel(size, channel_data, header.depth))
    alpha = _get_alpha_use(psd)
    mode = get_pil_mode(header.color_mode.name)
    if mode == 'P':
        image = Image.merge('L', channels[:get_pil_channels(mode)])
        image.putpalette(psd.color_mode_data.interleave())
    elif mode == 'MULTICHANNEL':
        image = channels[0]  # Multi-channel mode is a collection of alpha.
    else:
        image = Image.merge(mode, channels[:get_pil_channels(mode)])
    if mode == 'CMYK':
        image = image.point(lambda x: 255 - x)
    if apply_icc and 'ICC_PROFILE' in psd.image_resources:
        image = _apply_icc(image, psd.image_resources.get_data('ICC_PROFILE'))
    if alpha and mode in ('L', 'RGB'):
        image.putalpha(channels[-1])
    return _remove_white_background(image)
1012114
def convert(self, image, output=None):
        
        return self._convert(image, image.replace(Path(image).suffix, '.pdf') if not output else output)
442365
def convert_image(from_file, to_file, image_format):
    """"""
    with Image(filename=from_file) as original:
        with original.convert(image_format) as converted:
            converted.save(filename=to_file)
    return to_file
1307108
def toPIL(self, **attribs):
        
        import PIL.Image
        bytes = self.convert("png")
        sfile = io.BytesIO(bytes)
        pil = PIL.Image.open(sfile)
        return pil
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
897308
def upix_to_pix(upix):
    """"""
    nside = np.power(2, np.floor(np.log2(upix / 4)) / 2).astype(int)
    pix = upix - 4 * np.power(nside, 2)
    return pix, nside
605705
def save_image(self, cat, img, data):
        """"""
        filename = self.path(cat, img)
        mkdir(filename)
        if type(data) == np.ndarray:
            data = Image.fromarray(data).convert('RGB')
        data.save(filename)
1027541
private BufferedImage convertImage(BufferedImage image)
    {
        if (image.getType() == BufferedImage.TYPE_INT_RGB)
        {
            return image;
        }
        else
        {
            BufferedImage newImage = new BufferedImage(image.getWidth(),
                                                       image.getHeight(),
                                                       BufferedImage.TYPE_INT_RGB);
            newImage.getGraphics().drawImage(image, 0, 0, null);
            return newImage;
        }
    }