Converts the given image into a dict convertible to tf example.
483454
def encode_example(self, video_or_path_or_fobj):
    """"""
    if isinstance(video_or_path_or_fobj, six.string_types):
      if not os.path.isfile(video_or_path_or_fobj):
        _, video_temp_path = tempfile.mkstemp()
        try:
          tf.gfile.Copy(video_or_path_or_fobj, video_temp_path, overwrite=True)
          encoded_video = self._ffmpeg_decode(video_temp_path)
        finally:
          os.unlink(video_temp_path)
      else:
        encoded_video = self._ffmpeg_decode(video_or_path_or_fobj)
    elif hasattr(video_or_path_or_fobj, 'read'):
      encoded_video = self._ffmpeg_decode(video_or_path_or_fobj)
    else:
      encoded_video = video_or_path_or_fobj
    return super(Video, self).encode_example(encoded_video)
266268
def to_serialized_field(tensor_info):
  """"""
  # Select the type
  dtype = tensor_info.dtype

  # TODO(b/119937875): TF Examples proto only support int64, float32 and string
  # This create limitation like float64 downsampled to float32, bool converted
  # to int64 which is space ineficient, no support for complexes or quantized
  if tensor_info.dtype.is_integer or tensor_info.dtype.is_bool:
    dtype = tf.int64
  elif tensor_info.dtype.is_floating:
    dtype = tf.float32
  # It seems quite space inefficient to convert bool to int64
  # We may want to add support for complex, quantize dtype in the future

  # TFRecord only support 3 types
  if dtype not in (tf.int64, tf.float32, tf.string):
    raise NotImplementedError(
        'Serialization not implemented for {}'.format(dtype))

  # Select the feature proto type in function of the unknown shape
  if (tensor_info.shape is not None and  # Shape is a sequence (None, ...)
      tensor_info.shape.count(None) == 1 and
      tensor_info.shape[0] is None):
    return tf.io.FixedLenSequenceFeature(
        shape=tensor_info.shape[1:],
        dtype=dtype,
        allow_missing=True,
    )
  # At least one dimension is undefined
  elif tensor_info.shape is None or None in tensor_info.shape:
    return tf.io.VarLenFeature(dtype=dtype)
  else:
    return tf.io.FixedLenFeature(
        shape=tensor_info.shape,
        dtype=dtype,
    )
862796
def _load_image(cls, rkey):
        """"""

        v = cls._stock[rkey]
        img = None
        itype = v['type']
        if itype in ('stock', 'data'):
            img = tk.PhotoImage(format=v['format'], data=v['data'])
        elif itype == 'created':
            img = v['image']
        else:
            img = tk.PhotoImage(file=v['filename'])
        cls._cached[rkey] = img
        logger.info('Loaded resource %s.' % rkey)
        return img
533843
def serialize_example(transformed_json_data, info_dict):
  
  import six
  import tensorflow as tf

  def _make_int64_list(x):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=x))
  def _make_bytes_list(x):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=x))
  def _make_float_list(x):
    return tf.train.Feature(float_list=tf.train.FloatList(value=x))

  if sorted(six.iterkeys(transformed_json_data)) != sorted(six.iterkeys(info_dict)):
    raise ValueError('Keys do not match %s, %s' % (list(six.iterkeys(transformed_json_data)),
                     list(six.iterkeys(info_dict))))

  ex_dict = {}
  for name, info in six.iteritems(info_dict):
    if info['dtype'] == tf.int64:
      ex_dict[name] = _make_int64_list(transformed_json_data[name])
    elif info['dtype'] == tf.float32:
      ex_dict[name] = _make_float_list(transformed_json_data[name])
    elif info['dtype'] == tf.string:
      ex_dict[name] = _make_bytes_list(transformed_json_data[name])      
    else:
      raise ValueError('Unsupported data type %s' % info['dtype'])

  ex = tf.train.Example(features=tf.train.Features(feature=ex_dict))
  return ex.SerializeToString()
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)}
807821
def decode_example(self, tfexample_data):
    """"""
    # TODO(epot): Support dynamic shape
    if self.shape.count(None) < 2:
      # Restore the shape if possible. TF Example flattened it.
      shape = [-1 if i is None else i for i in self.shape]
      tfexample_data = tf.reshape(tfexample_data, shape)
    if tfexample_data.dtype != self.dtype:
      tfexample_data = tf.dtypes.cast(tfexample_data, self.dtype)
    return tfexample_data
1316539
def convert_to_odl(image):
    """"""

    shape = image.shape

    if len(shape) == 2:
        space = odl.uniform_discr([0, 0], shape, shape)
    elif len(shape) == 3:
        d = shape[2]
        shape = shape[:2]
        image = np.transpose(image, (2, 0, 1))
        space = odl.uniform_discr([0, 0], shape, shape) ** d

    image = space.element(image)

    return image
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
310854
def image(image_format, doc=None):
    """"""
    @on_valid('image/{0}'.format(image_format))
    def image_handler(data, **kwargs):
        if hasattr(data, 'read'):
            return data
        elif hasattr(data, 'save'):
            output = stream()
            if introspect.takes_all_arguments(data.save, 'format') or introspect.takes_kwargs(data.save):
                data.save(output, format=image_format.upper())
            else:
                data.save(output)
            output.seek(0)
            return output
        elif hasattr(data, 'render'):
            return data.render()
        elif os.path.isfile(data):
            return open(data, 'rb')

    image_handler.__doc__ = doc or "{0} formatted image".format(image_format)
    return image_handler
816189
def _generate_examples(self, images_dir_path):
    
    parent_dir = tf.io.gfile.listdir(images_dir_path)[0]
    walk_dir = os.path.join(images_dir_path, parent_dir)
    dirs = tf.io.gfile.listdir(walk_dir)

    for d in dirs:
      if tf.io.gfile.isdir(os.path.join(walk_dir, d)):
        for full_path, _, fname in tf.io.gfile.walk(os.path.join(walk_dir, d)):
          for image_file in fname:
            if image_file.endswith(".jpg"):
              image_path = os.path.join(full_path, image_file)
              yield {
                  "image": image_path,
                  "label": d.lower(),
              }
753524
def to_image_list(tensors, size_divisible=0):
    
    if isinstance(tensors, torch.Tensor) and size_divisible > 0:
        tensors = [tensors]

    if isinstance(tensors, ImageList):
        return tensors
    elif isinstance(tensors, torch.Tensor):
        # single tensor shape can be inferred
        assert tensors.dim() == 4
        image_sizes = [tensor.shape[-2:] for tensor in tensors]
        return ImageList(tensors, image_sizes)
    elif isinstance(tensors, (tuple, list)):
        max_size = tuple(max(s) for s in zip(*[img.shape for img in tensors]))

        # TODO Ideally, just remove this and let me model handle arbitrary
        # input sizs
        if size_divisible > 0:
            import math

            stride = size_divisible
            max_size = list(max_size)
            max_size[1] = int(math.ceil(max_size[1] / stride) * stride)
            max_size[2] = int(math.ceil(max_size[2] / stride) * stride)
            max_size = tuple(max_size)

        batch_shape = (len(tensors),) + max_size
        batched_imgs = tensors[0].new(*batch_shape).zero_()
        for img, pad_img in zip(tensors, batched_imgs):
            pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)

        image_sizes = [im.shape[-2:] for im in tensors]

        return ImageList(batched_imgs, image_sizes)
    else:
        raise TypeError("Unsupported type for to_image_list: {}".format(type(tensors)))
449848
def tf_summary_to_dict(tf_summary_str_or_pb, namespace=""):
    
    values = {}
    if isinstance(tf_summary_str_or_pb, Summary):
        summary_pb = tf_summary_str_or_pb
    elif isinstance(tf_summary_str_or_pb, Event):
        summary_pb = tf_summary_str_or_pb.summary
        values["global_step"] = tf_summary_str_or_pb.step
        values["_timestamp"] = tf_summary_str_or_pb.wall_time
    else:
        summary_pb = Summary()
        summary_pb.ParseFromString(tf_summary_str_or_pb)

    for value in summary_pb.value:
        kind = value.WhichOneof("value")
        if kind == "simple_value":
            values[namespaced_tag(value.tag, namespace)] = value.simple_value
        elif kind == "image":
            from PIL import Image
            image = wandb.Image(Image.open(
                six.BytesIO(value.image.encoded_image_string)))
            tag_idx = value.tag.rsplit('/', 1)
            if len(tag_idx) > 1 and tag_idx[1].isdigit():
                tag, idx = tag_idx
                values.setdefault(history_image_key(tag), []).append(image)
            else:
                values[history_image_key(value.tag)] = image
        # Coming soon...
        # elif kind == "audio":
        #    audio = wandb.Audio(six.BytesIO(value.audio.encoded_audio_string),
        #                        sample_rate=value.audio.sample_rate, content_type=value.audio.content_type)
        elif kind == "histo":
            first = value.histo.bucket_limit[0] + \
                value.histo.bucket_limit[0] - value.histo.bucket_limit[1]
            last = value.histo.bucket_limit[-2] + \
                value.histo.bucket_limit[-2] - value.histo.bucket_limit[-3]
            np_histogram = (list(value.histo.bucket), [
                first] + value.histo.bucket_limit[:-1] + [last])
            values[namespaced_tag(value.tag)] = wandb.Histogram(
                np_histogram=np_histogram)

    return values
58485
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'fonts' in _dict:
            args['fonts'] = [
                FontSetting._from_dict(x) for x in (_dict.get('fonts'))
            ]
        if 'styles' in _dict:
            args['styles'] = [
                WordStyle._from_dict(x) for x in (_dict.get('styles'))
            ]
        return cls(**args)
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,
      }
366981
def fromTFExample(bytestr):
  """"""
  example = tf.train.Example()
  example.ParseFromString(bytestr)
  return example
1183602
def get_image(verbose=False):
  """"""
  base_data = tf.constant(image_data(verbose=verbose))
  base_image = tf.image.decode_image(base_data, channels=3)
  base_image.set_shape((IMAGE_HEIGHT, IMAGE_WIDTH, 3))
  parsed_image = tf.Variable(base_image, name='image', dtype=tf.uint8)
  return parsed_image
1248130
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'images_processed' in _dict:
            args['images_processed'] = _dict.get('images_processed')
        else:
            raise ValueError(
                'Required property \'images_processed\' not present in DetectedFaces JSON'
            )
        if 'images' in _dict:
            args['images'] = [
                ImageWithFaces._from_dict(x) for x in (_dict.get('images'))
            ]
        else:
            raise ValueError(
                'Required property \'images\' not present in DetectedFaces JSON'
            )
        if 'warnings' in _dict:
            args['warnings'] = [
                WarningInfo._from_dict(x) for x in (_dict.get('warnings'))
            ]
        return cls(**args)