Optimized jpg and png images

    :param pelican: The Pelican instance
549694
def optimize_images(pelican):
    
    for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
        for name in filenames:
            if os.path.splitext(name)[1] in COMMANDS.keys():
                optimize(dirpath, name)
787211
def convert(f, opts = {})
      opts = opts.dup
      f = f.to_s.downcase
      allowed = %w(jpeg jpg png)
      raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f)
      self.format_override = f == 'jpeg' ? 'jpg' : f
      opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality)
      write_opts.merge!(opts)
      get_image
    end
536667
def _pixel_data(image):
    
    # Test for PIL.Image and numpy.ndarray without requiring that cv2 or PIL
    # are installed.
    if 'PIL.' in str(type(image)):
        if 'L' != image.mode:
            image = image.convert('L')
        pixels = image.tobytes()
        width, height = image.size
    elif 'numpy.ndarray' in str(type(image)):
        if 3 == len(image.shape):
            # Take just the first channel
            image = image[:, :, 0]
        if 'uint8' != str(image.dtype):
            image = image.astype('uint8')
        try:
            pixels = image.tobytes()
        except AttributeError:
            # `numpy.ndarray.tobytes()` introduced in `numpy` 1.9.0 - use the
            # older `tostring` method.
            pixels = image.tostring()
        height, width = image.shape[:2]
    else:
        # image should be a tuple (pixels, width, height)
        pixels, width, height = image

        # Check dimensions
        if 0 != len(pixels) % (width * height):
            raise PyZbarError(
                (
                    'Inconsistent dimensions: image data of {0} bytes is not '
                    'divisible by (width x height = {1})'
                ).format(len(pixels), (width * height))
            )

    # Compute bits-per-pixel
    bpp = 8 * len(pixels) // (width * height)
    if 8 != bpp:
        raise PyZbarError(
            'Unsupported bits-per-pixel [{0}]. Only [8] is supported.'.format(
                bpp
            )
        )

    return pixels, width, height
369562
def match_via_correlation(image, template, raw_tolerance=1, normed_tolerance=0.9):
    
    h, w = image.shape
    th, tw = template.shape
    # fft based convolution enables fast matching of large images
    correlation = fftconvolve(image, template[::-1,::-1])
    # trim the returned image, fftconvolve returns an image of width: (Temp_w-1) + Im_w + (Temp_w -1), likewise height
    correlation = correlation[th-1:h, tw-1:w]
    # find images regions which are potentially matches
    match_position_dict = get_tiles_at_potential_match_regions(image, template, correlation, raw_tolerance=raw_tolerance)
    # bright spots in images can lead to false positivies- the normalisation carried out here eliminates those
    results = normalise_correlation(match_position_dict, correlation, template, normed_tolerance=normed_tolerance)
    return results
346320
def edit_imagefindpars():
    
    teal.teal(imagefindpars.__taskname__, returnAs=None,
              autoClose=True, loadOnly=False, canExecute=False)
641205
def _tile_image(self, data):
        
        image = Image.open(BytesIO(data))
        return image.convert('RGBA')
1350594
def rescale_pixel_values(images, order="C"):
    
    images = np.asarray(images, order=order).astype("float32")
    images -= images.min()
    images /= images.max()
    return images
254250
def pngout(ext_args):
    """"""
    args = _PNGOUT_ARGS + [ext_args.old_filename, ext_args.new_filename]
    extern.run_ext(args)
    return _PNG_FORMAT
374839
def pad_image(arr, max_size=400):
    """"""
    dim = np.max(arr.shape)
    img = np.zeros((dim, dim, 3), dtype=arr.dtype)
    xl = (dim - arr.shape[0]) // 2
    yl = (dim - arr.shape[1]) // 2
    img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
    return resample_image(img, max_size=max_size)
538932
def optimize_image(arg):
    """"""
    try:
        filename, image_format, settings = arg

        Settings.update(settings)

        format_module, nag_about_gifs = _get_format_module(image_format)

        if format_module is None:
            if Settings.verbose > 1:
                print(filename, image_format)  # image.mode)
                print("\tFile format not selected.")
            return None

        report_stats = _optimize_with_progs(format_module, filename,
                                            image_format)
        report_stats.nag_about_gifs = nag_about_gifs
        stats.report_saved(report_stats)
        return report_stats
    except Exception as exc:
        print(exc)
        traceback.print_exc()
        return stats.ReportStats(filename, error="Optimizing Image")
922793
def image_embedding(images,
                    model_fn=resnet_v1_152,
                    trainable=True,
                    is_training=True,
                    weight_decay=0.0001,
                    batch_norm_decay=0.997,
                    batch_norm_epsilon=1e-5,
                    batch_norm_scale=True,
                    add_summaries=False,
                    reuse=False):
  """"""

  is_resnet_training = trainable and is_training

  batch_norm_params = {
      "is_training": is_resnet_training,
      "trainable": trainable,
      "decay": batch_norm_decay,
      "epsilon": batch_norm_epsilon,
      "scale": batch_norm_scale,
  }

  if trainable:
    weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
  else:
    weights_regularizer = None

  with tf.variable_scope(model_fn.__name__, [images], reuse=reuse) as scope:
    with slim.arg_scope(
        [slim.conv2d],
        weights_regularizer=weights_regularizer,
        trainable=trainable):
      with slim.arg_scope(
          [slim.conv2d],
          weights_initializer=slim.variance_scaling_initializer(),
          activation_fn=tf.nn.relu,
          normalizer_fn=slim.batch_norm,
          normalizer_params=batch_norm_params):
        with slim.arg_scope([slim.batch_norm],
                            is_training=is_resnet_training,
                            trainable=trainable):
          with slim.arg_scope([slim.max_pool2d], padding="SAME"):
            net, end_points = model_fn(
                images, num_classes=None, global_pool=False,
                is_training=is_resnet_training,
                reuse=reuse, scope=scope)

  if add_summaries:
    for v in end_points.values():
      tf.contrib.layers.summaries.summarize_activation(v)

  return net
422103
def function(self,p):
        """"""
        int_index=int(len(p.generators)*wrap(0,1.0,p.index))
        pg=p.generators[int_index]

        image_array = pg(xdensity=p.xdensity,ydensity=p.ydensity,bounds=p.bounds,
                         x=p.x+p.size*(pg.x*np.cos(p.orientation)-pg.y*np.sin(p.orientation)),
                         y=p.y+p.size*(pg.x*np.sin(p.orientation)+pg.y*np.cos(p.orientation)),
                         orientation=pg.orientation+p.orientation,size=pg.size*p.size,
                         scale=pg.scale*p.scale,offset=pg.offset+p.offset)

        return image_array
742425
def png(out, metadata, f):
    

    import png

    pixels, meta = pixmeta(metadata, f)
    p = png.Writer(**meta)
    p.write(out, pixels)
631225
def extract_images_generic(pike, root, log, options):
    """"""

    jpegs = []
    pngs = []
    for _, xref, ext in extract_images(pike, root, log, options, extract_image_generic):
        log.debug('xref = %s ext = %s', xref, ext)
        if ext == '.png':
            pngs.append(xref)
        elif ext == '.jpg':
            jpegs.append(xref)
    log.debug("Optimizable images: JPEGs: %s PNGs: %s", len(jpegs), len(pngs))
    return jpegs, pngs
255119
def _generate_examples(self, archive):
    

    for fname, fobj in archive:
      res = _NAME_RE.match(fname)
      if not res:  # if anything other than .png; skip
        continue
      label = res.group(2).lower()
      yield {
          "image": fobj,
          "label": label,
      }
770076
def file_to_png(fp):
	
	import PIL.Image # pylint: disable=import-error
	with io.BytesIO() as dest:
		PIL.Image.open(fp).save(dest, "PNG", optimize=True)
		return dest.getvalue()
294670
def pixbuf_to_cairo_png(pixbuf):
    
    buffer_pointer = ffi.new('gchar **')
    buffer_size = ffi.new('gsize *')
    error = ffi.new('GError **')
    handle_g_error(error, pixbuf.save_to_buffer(
        buffer_pointer, buffer_size, ffi.new('char[]', b'png'), error,
        ffi.new('char[]', b'compression'), ffi.new('char[]', b'0'),
        ffi.NULL))
    png_bytes = ffi.buffer(buffer_pointer[0], buffer_size[0])
    return ImageSurface.create_from_png(BytesIO(png_bytes))