Spec for each image
501008
def image_spec(self):
        """"""
        from harpoon.option_spec import image_specs as specs
        from harpoon.option_spec import image_objs
        class persistence_shell_spec(Spec):
            """Make the persistence shell default to the shell on the image"""
            def normalise(self, meta, val):
                shell = defaulted(string_spec(), "/bin/bash").normalise(meta, meta.everything[["images", meta.key_names()["_key_name_2"]]].get("shell", NotSpecified))
                shell = defaulted(formatted(string_spec(), formatter=MergedOptionStringFormatter), shell).normalise(meta, val)
                return shell

        return create_spec(image_objs.Image
            , validators.deprecated_key("persistence", "The persistence feature has been removed")
            , validators.deprecated_key("squash_after", "The squash feature has been removed")
            , validators.deprecated_key("squash_before_push", "The squash feature has been removed")

            # Changed how volumes_from works
            , validators.deprecated_key("volumes_from", "Use ``volumes.share_with``")

            # Deprecated link
            , validators.deprecated_key("link", "Use ``links``")

            # Harpoon options
            , harpoon = any_spec()

            # default the name to the key of the image
            , tag = optional_spec(formatted(string_spec(), formatter=MergedOptionStringFormatter))
            , name = formatted(defaulted(string_spec(), "{_key_name_1}"), formatter=MergedOptionStringFormatter)
            , key_name = formatted(overridden("{_key_name_1}"), formatter=MergedOptionStringFormatter)
            , image_name = optional_spec(string_spec())
            , image_index = formatted(defaulted(string_spec(), ""), formatter=MergedOptionStringFormatter)
            , container_name = optional_spec(string_spec())
            , image_name_prefix = defaulted(string_spec(), "")

            , no_tty_option = defaulted(formatted(boolean(), formatter=MergedOptionStringFormatter), False)

            , user = defaulted(string_spec(), None)
            , configuration = any_spec()

            , vars = dictionary_spec()
            , assume_role = optional_spec(formatted(string_spec(), formatter=MergedOptionStringFormatter))
            , deleteable_image = defaulted(boolean(), False)

            , authentication = self.authentications_spec

            # The spec itself
            , shell = defaulted(formatted(string_spec(), formatter=MergedOptionStringFormatter), "/bin/bash")
            , bash = delayed(optional_spec(formatted(string_spec(), formatter=MergedOptionStringFormatter)))
            , command = delayed(optional_spec(formatted(string_spec(), formatter=MergedOptionStringFormatter)))
            , commands = required(container_spec(Commands, listof(command_spec())))
            , cache_from = delayed(or_spec(boolean(), listof(formatted(string_spec(), formatter=MergedOptionStringFormatter))))
            , cleanup_intermediate_images = defaulted(boolean(), True)

            , links = listof(specs.link_spec(), expect=image_objs.Link)

            , context = self.context_spec
            , wait_condition = optional_spec(self.wait_condition_spec)

            , lxc_conf = defaulted(filename_spec(), None)

            , volumes = create_spec(image_objs.Volumes
                , mount = listof(specs.mount_spec(), expect=image_objs.Mount)
                , share_with = listof(formatted(string_spec(), MergedOptionStringFormatter, expected_type=image_objs.Image))
                )

            , dependency_options = dictof(specs.image_name_spec()
                , create_spec(image_objs.DependencyOptions
                  , attached = defaulted(boolean(), False)
                  , wait_condition = optional_spec(self.wait_condition_spec)
                  )
                )

            , env = listof(specs.env_spec(), expect=image_objs.Environment)
            , ports = listof(specs.port_spec(), expect=image_objs.Port)
            , ulimits = defaulted(listof(dictionary_spec()), None)
            , log_config = defaulted(listof(dictionary_spec()), None)
            , security_opt = defaulted(listof(string_spec()), None)
            , read_only_rootfs = defaulted(boolean(), False)

            , other_options = create_spec(other_options
                , start = dictionary_spec()
                , build = dictionary_spec()
                , create = dictionary_spec()
                , host_config = dictionary_spec()
                )

            , network = create_spec(image_objs.Network
                , dns = defaulted(listof(string_spec()), None)
                , mode = defaulted(string_spec(), None)
                , hostname = defaulted(string_spec(), None)
                , domainname = defaulted(string_spec(), None)
                , disabled = defaulted(boolean(), False)
                , dns_search = defaulted(listof(string_spec()), None)
                , extra_hosts = listof(string_spec())
                , network_mode = defaulted(string_spec(), None)
                , publish_all_ports = defaulted(boolean(), False)
                )

            , cpu = create_spec(image_objs.Cpu
                , cap_add = defaulted(listof(string_spec()), None)
                , cpuset_cpus = defaulted(string_spec(), None)
                , cpuset_mems = defaulted(string_spec(), None)
                , cap_drop = defaulted(listof(string_spec()), None)
                , mem_limit = defaulted(integer_spec(), 0)
                , cpu_shares = defaulted(integer_spec(), None)
                , memswap_limit = defaulted(integer_spec(), 0)
                )

            , devices = defaulted(listof(dictionary_spec()), None)
            , privileged = defaulted(boolean(), False)
            , restart_policy = defaulted(string_spec(), None)
            )
717074
def read_image(img_spec, bkground_thresh, ensure_num_dim=3):
    """"""

    img = load_image_from_disk(img_spec)

    if not np.issubdtype(img.dtype, np.floating):
        img = img.astype('float32')

    if ensure_num_dim == 3:
        img = check_image_is_3d(img)
    elif ensure_num_dim == 4:
        img = check_image_is_4d(img)

    return threshold_image(img, bkground_thresh)
960191
def _spec(self, name):
        ""
        for s in self._framespec:
            if s.name == name:
                return s
        raise ValueError("Unknown spec: " + name)
1236903
def norm(image):
    """"""
    min_value = image.min()
    max_value = image.max()
    if min_value == max_value:
        return image - min_value
    return (image - min_value) / (max_value - min_value)
838847
function getImageDataType (image) {
  if (image.color) {
    return 'rgb';
  }

  const pixelData = image.getPixelData();

  if (pixelData instanceof Int16Array) {
    return 'int16';
  }

  if (pixelData instanceof Uint16Array) {
    return 'uint16';
  }

  if (pixelData instanceof Int8Array) {
    return 'int8';
  }

  return 'uint8';
}
1079484
def _validate_pixel_density(self):
        
        for f in [f for f in self.mets.find_files() if f.mimetype.startswith('image/')]:
            if not f.local_filename and not self.download:
                self.report.add_notice("Won't download remote image <%s>" % f.url)
                continue
            exif = self.workspace.resolve_image_exif(f.url)
            for k in ['xResolution', 'yResolution']:
                v = exif.__dict__.get(k)
                if v is None or v <= 72:
                    self.report.add_error("Image %s: %s (%s pixels per %s) is too low" % (f.ID, k, v, exif.resolutionUnit))
27357
def get_spec_list(image_specs, container_args):
    

    spec_list = [spec.strip() for spec in image_specs.split('|')]
    original_count = len(spec_list)

    if 'count' in container_args:
        if 'count_offset' in container_args:
            spec_list = spec_list[container_args['count_offset']:]
        spec_list = spec_list[:container_args['count']]

    return spec_list, original_count
1216536
def get_image_sizes(image):
    """"""

    # It is possible to have the same width appear more than once, if
    # THUMBNAIL_UPSCALE is set to False and the image's width is less than the
    # largest value in FLEXIBLE_IMAGE_SIZES. So keep track of widths and
    # don't output more than one image with the same width (which would result
    # in an invalid `srcset` attribute).
    sizes = []
    seen_widths = []

    for size in settings_sizes():
        img = get_thumbnail_shim(image, size)

        if img.width in seen_widths:
            continue

        seen_widths.append(img.width)

        sizes.append({
            "url": img.url,
            "width": img.width,
            "height": img.height,
        })
    return sizes
1060951
def get_image_tags(context, instance, options):
    
    if hasattr(instance, 'image') and hasattr(instance.image, 'exif'):
        aspect_ratio = compute_aspect_ratio(instance.image)
    elif 'image' in instance.glossary and 'width' in instance.glossary['image']: 
        aspect_ratio = compute_aspect_ratio_with_glossary(instance.glossary)
        instance.glossary['ramdom_svg_color'] = 'hsl({}, 30%, 80%, 0.8)'.format( str(random.randint(0, 360)))
    else:
        # if accessing the image file fails or fake image fails, abort here
        logger.warning("Unable to compute aspect ratio of image '{}'".format(instance.image))
        return

    is_responsive = options.get('is_responsive', False)
    resize_options = options.get('resize_options', {})
    crop = 'crop' in resize_options
    upscale = 'upscale' in resize_options
    if hasattr(instance.image, 'subject_location'):
        subject_location = instance.image.subject_location and 'subject_location' in resize_options
    else:
        subject_location = None
    resolutions = (False, True) if 'high_resolution' in resize_options else (False,)
    tags = {'sizes': [], 'srcsets': {}, 'is_responsive': is_responsive, 'extra_styles': {}}
    if is_responsive:
        image_width = parse_responsive_length(options.get('image_width_responsive') or '100%')
        assert(image_width[1]), "The given image has no valid width"
        if image_width[1] != 1.0:
            tags['extra_styles'].update({'max-width': '{:.0f}%'.format(100 * image_width[1])})
    else:
        image_width = parse_responsive_length(options['image_width_fixed'])
        if not image_width[0]:
            image_width = (instance.image.width, image_width[1])
    try:
        image_height = parse_responsive_length(options['image_height'])
    except KeyError:
        image_height = (None, None)
    set_defaults(options)
    if is_responsive:
        max_width = 0
        for bp in options['breakpoints']:
            if bp not in options['container_max_widths']:
                continue
            width = int(image_width[1] * options['container_max_widths'][bp])
            max_width = max(max_width, width)
            size = get_image_size(width, image_height, aspect_ratio)
            if bp in options['media_queries']:
                tags['sizes'].append('{0} {1}px'.format(' and '.join(options['media_queries'][bp]), width))
            for high_res in resolutions:
                if high_res:
                    size = (size[0] * 2, size[1] * 2)
                key = '{0}w'.format(size[0])
                tags['srcsets'][key] = {'size': size, 'crop': crop, 'upscale': upscale,
                                        'subject_location': subject_location}
        # use an existing image as fallback for the <img ...> element
        if not max_width > 0:
            logger.warning('image tags: image max width is zero')
        size = (int(round(max_width)), int(round(max_width * aspect_ratio)))
    else:
        size = get_image_size(image_width[0], image_height, aspect_ratio)
        if len(resolutions) > 1:
            for high_res in resolutions:
                if high_res:
                    tags['srcsets']['2x'] = {'size': (size[0] * 2, size[1] * 2), 'crop': crop,
                        'upscale': upscale, 'subject_location': subject_location}
                else:
                    tags['srcsets']['1x'] = {'size': size, 'crop': crop,
                        'upscale': upscale, 'subject_location': subject_location}
    tags['src'] = {'size': size, 'crop': crop, 'upscale': upscale,
                   'subject_location': subject_location}
    return tags
1280940
private static void adjustQualityFromImage(Map<String, Float> pFormatQuality, BufferedImage pImage) {
        // NOTE: The values are all made-up. May need tuning.

        // If pImage.getColorModel() instanceof IndexColorModel
        //    JPEG qs*=0.6
        //    If NOT binary or 2 color index
        //        WBMP qs*=0.5
        // Else
        //    GIF qs*=0.02
        //    PNG qs*=0.9 // JPEG is smaller/faster
        if (pImage.getColorModel() instanceof IndexColorModel) {
            adjustQuality(pFormatQuality, FORMAT_JPEG, 0.6f);

            if (pImage.getType() != BufferedImage.TYPE_BYTE_BINARY ||  ((IndexColorModel) pImage.getColorModel()).getMapSize() != 2) {
                adjustQuality(pFormatQuality, FORMAT_WBMP, 0.5f);
            }
        }
        else {
            adjustQuality(pFormatQuality, FORMAT_GIF, 0.01f);
            adjustQuality(pFormatQuality, FORMAT_PNG, 0.99f); // JPEG is smaller/faster
        }

        // If pImage.getColorModel().hasTransparentPixels()
        //    JPEG qs*=0.05
        //    WBMP qs*=0.05
        //    If NOT transparency == BITMASK
        //        GIF qs*=0.8
        if (ImageUtil.hasTransparentPixels(pImage, true)) {
            adjustQuality(pFormatQuality, FORMAT_JPEG, 0.009f);
            adjustQuality(pFormatQuality, FORMAT_WBMP, 0.009f);

            if (pImage.getColorModel().getTransparency() != Transparency.BITMASK) {
                adjustQuality(pFormatQuality, FORMAT_GIF, 0.8f);
            }
        }
    }
473299
def _normalize_images(self):
        
        if 'image' not in self.data:
            return
        for img in self.data['image']:
            fname = img['file'].replace('_', ' ')
            fstart = fname.startswith('File:')
            istart = fname.startswith('Image:')
            if not fstart and not istart:
                fname = 'File:' + fname
                img['orig'] = img['file']
                img['file'] = fname
1294268
def showSpec(self, fname):
        """"""
        if not self.specPlot.hasImg() and fname is not None:
            self.specPlot.fromFile(fname)
399560
def _parse_example_spec(self):
    """"""
    height, width = image_util.get_expected_image_size(self.module_spec)
    input_shape = [height, width, 3]
    return {self.key: tf_v1.FixedLenFeature(input_shape, tf.float32)}
463841
def get_image(self, img, is_train):
        """"""
        img_arr = mx.image.imread(img)
        img_arr = transform(img_arr, 256, 256, is_train, self.boxes[img])
        return img_arr
292322
def image(self, img):
        """"""
        if img.mode != '1':
            raise ValueError('Image must be in mode 1.')
        imwidth, imheight = img.size
        if imwidth != self.width or imheight != self.height:
            raise ValueError('Image must be same dimensions as display ({0}x{1}).' \
                .format(self.width, self.height))
        # Grab all the pixels from the image, faster than getpixel.
        pixels = img.load()
        # Clear buffer
        for i in range(len(self.buf)):
            self.buf[i] = 0
        # Iterate through the pixels
        for x in range(self.width):       # yes this double loop is slow,
            for y in range(self.height):  #  but these displays are small!
                if pixels[(x, y)]:
                    self.pixel(x, y, 1)
1064135
def _all_spec(self):
        

        base = self._mod_spec

        for spec in self.basic_spec:
            base[spec] = self.basic_spec[spec]

        return base
411276
def image_rmse(predictions, labels, weights_fn=common_layers.weights_all):
  """"""
  if common_layers.shape_list(predictions)[-1] == 1:
    predictions = tf.squeeze(predictions, axis=[-1])
  else:
    predictions = tf.argmax(predictions, axis=-1)
  return padded_rmse(predictions, labels, weights_fn)