當前位置: 首頁>>代碼示例>>Python>>正文


Python v1.uint8方法代碼示例

本文整理匯總了Python中tensorflow.compat.v1.uint8方法的典型用法代碼示例。如果您正苦於以下問題:Python v1.uint8方法的具體用法?Python v1.uint8怎麽用?Python v1.uint8使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在tensorflow.compat.v1的用法示例。


在下文中一共展示了v1.uint8方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _process_image

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def _process_image(coder, name):
  """Process a single image file.

  If name is "train", a black image is returned. Otherwise, a white image is
  returned.

  Args:
    coder: instance of ImageCoder to provide TensorFlow image coding utils.
    name: string, unique identifier specifying the data set.
  Returns:
    image_buffer: bytes, JPEG encoding of RGB image.
    height: integer, image height in pixels.
    width: integer, image width in pixels.
  """
  # Read the image file.
  value = 0 if name == 'train' else 255
  height = random.randint(30, 299)
  width = random.randint(30, 299)
  image = np.full((height, width, 3), value, np.uint8)

  jpeg_data = coder.encode_jpeg(image)

  return jpeg_data, height, width 
開發者ID:tensorflow,項目名稱:benchmarks,代碼行數:25,代碼來源:tfrecord_image_generator.py

示例2: preprocess

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def preprocess(self, image_buffer, bbox, batch_position):
    """Preprocessing image_buffer as a function of its batch position."""
    if self.train:
      image = train_image(image_buffer, self.height, self.width, bbox,
                          batch_position, self.resize_method, self.distortions,
                          None, summary_verbosity=self.summary_verbosity,
                          distort_color_in_yiq=self.distort_color_in_yiq,
                          fuse_decode_and_crop=self.fuse_decode_and_crop)
    else:
      image = tf.image.decode_jpeg(
          image_buffer, channels=3, dct_method='INTEGER_FAST')
      image = eval_image(image, self.height, self.width, batch_position,
                         self.resize_method,
                         summary_verbosity=self.summary_verbosity)
    # Note: image is now float32 [height,width,3] with range [0, 255]

    # image = tf.cast(image, tf.uint8) # HACK TESTING

    if self.match_mlperf:
      mlperf.logger.log(key=mlperf.tags.INPUT_MEAN_SUBTRACTION,
                        value=_CHANNEL_MEANS)
      normalized = image - _CHANNEL_MEANS
    else:
      normalized = normalized_image(image)
    return tf.cast(normalized, self.dtype) 
開發者ID:tensorflow,項目名稱:benchmarks,代碼行數:27,代碼來源:preprocessing.py

示例3: image_summary

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def image_summary(predictions, targets, hparams):
  """Reshapes predictions and passes it to tensorboard.

  Args:
    predictions : The predicted image (logits).
    targets : The ground truth.
    hparams: model hparams.

  Returns:
    summary_proto: containing the summary images.
    weights: A Tensor of zeros of the same shape as predictions.
  """
  del hparams
  results = tf.cast(tf.argmax(predictions, axis=-1), tf.uint8)
  gold = tf.cast(targets, tf.uint8)
  summary1 = tf.summary.image("prediction", results, max_outputs=2)
  summary2 = tf.summary.image("data", gold, max_outputs=2)
  summary = tf.summary.merge([summary1, summary2])
  return summary, tf.zeros_like(predictions) 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:21,代碼來源:metrics.py

示例4: tpu_safe_image_summary

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def tpu_safe_image_summary(image):
  if is_xla_compiled():
    # We only support float32 images at the moment due to casting complications.
    if image.dtype != tf.float32:
      image = to_float(image)
  else:
    image = tf.cast(image, tf.uint8)
  return image


# This has been (shamefully) copied from
# GitHub tensorflow/models/blob/master/research/slim/nets/cyclegan.py
#
# tensorflow/models cannot be pip installed, and even if it were we don't want
# to depend on all the models in it.
#
# Therefore copying and forgoing any more bugfixes into it is the most
# expedient way to use this function. 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:20,代碼來源:common_layers.py

示例5: _encode_gif

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def _encode_gif(images, fps):
  """Encodes numpy images into gif string.

  Args:
    images: A 4-D `uint8` `np.array` (or a list of 3-D images) of shape
      `[time, height, width, channels]` where `channels` is 1 or 3.
    fps: frames per second of the animation

  Returns:
    The encoded gif string.

  Raises:
    IOError: If the ffmpeg command returns an error.
  """
  writer = WholeVideoWriter(fps)
  writer.write_multi(images)
  return writer.finish() 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:19,代碼來源:common_video.py

示例6: __init__

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def __init__(self, batch_size, *args, **kwargs):
    self._store_rollouts = kwargs.pop("store_rollouts", True)

    super(T2TEnv, self).__init__(*args, **kwargs)

    self.batch_size = batch_size
    self._rollouts_by_epoch_and_split = collections.OrderedDict()
    self.current_epoch = None
    self._should_preprocess_on_reset = True
    with tf.Graph().as_default() as tf_graph:
      self._tf_graph = _Noncopyable(tf_graph)
      self._decoded_image_p = _Noncopyable(
          tf.placeholder(dtype=tf.uint8, shape=(None, None, None))
      )
      self._encoded_image_t = _Noncopyable(
          tf.image.encode_png(self._decoded_image_p.obj)
      )
      self._encoded_image_p = _Noncopyable(tf.placeholder(tf.string))
      self._decoded_image_t = _Noncopyable(
          tf.image.decode_png(self._encoded_image_p.obj)
      )
      self._session = _Noncopyable(tf.Session()) 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:24,代碼來源:gym_env.py

示例7: image_to_tf_summary_value

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def image_to_tf_summary_value(image, tag):
  """Converts a NumPy image to a tf.Summary.Value object.

  Args:
    image: 3-D NumPy array.
    tag: name for tf.Summary.Value for display in tensorboard.
  Returns:
    image_summary: A tf.Summary.Value object.
  """
  curr_image = np.asarray(image, dtype=np.uint8)
  height, width, n_channels = curr_image.shape
  # If monochrome image, then reshape to [height, width]
  if n_channels == 1:
    curr_image = np.reshape(curr_image, [height, width])
  s = io.BytesIO()
  matplotlib_pyplot().imsave(s, curr_image, format="png")
  img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
                             height=height, width=width,
                             colorspace=n_channels)
  return tf.Summary.Value(tag=tag, image=img_sum) 
開發者ID:tensorflow,項目名稱:tensor2tensor,代碼行數:22,代碼來源:image_utils.py

示例8: _extract_images

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def _extract_images(filename, num_images):
  """Extract the images into a numpy array.

  Args:
    filename: The path to an MNIST images file.
    num_images: The number of images in the file.

  Returns:
    A numpy array of shape [number_of_images, height, width, channels].
  """
  print('Extracting images from: ', filename)
  with gzip.open(filename) as bytestream:
    bytestream.read(16)
    buf = bytestream.read(
        _IMAGE_SIZE * _IMAGE_SIZE * num_images * _NUM_CHANNELS)
    data = np.frombuffer(buf, dtype=np.uint8)
    data = data.reshape(num_images, _IMAGE_SIZE, _IMAGE_SIZE, _NUM_CHANNELS)
  return data 
開發者ID:google-research,項目名稱:morph-net,代碼行數:20,代碼來源:download_and_convert_mnist.py

示例9: _extract_labels

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def _extract_labels(filename, num_labels):
  """Extract the labels into a vector of int64 label IDs.

  Args:
    filename: The path to an MNIST labels file.
    num_labels: The number of labels in the file.

  Returns:
    A numpy array of shape [number_of_labels]
  """
  print('Extracting labels from: ', filename)
  with gzip.open(filename) as bytestream:
    bytestream.read(8)
    buf = bytestream.read(1 * num_labels)
    labels = np.frombuffer(buf, dtype=np.uint8).astype(np.int64)
  return labels 
開發者ID:google-research,項目名稱:morph-net,代碼行數:18,代碼來源:download_and_convert_mnist.py

示例10: _decode_masks

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def _decode_masks(self, parsed_tensors):
    """Decode a set of PNG masks to the tf.float32 tensors."""
    def _decode_png_mask(png_bytes):
      mask = tf.squeeze(
          tf.io.decode_png(png_bytes, channels=1, dtype=tf.uint8), axis=-1)
      mask = tf.cast(mask, dtype=tf.float32)
      mask.set_shape([None, None])
      return mask

    height = parsed_tensors['image/height']
    width = parsed_tensors['image/width']
    masks = parsed_tensors['image/object/mask']
    return tf.cond(
        tf.greater(tf.size(masks), 0),
        lambda: tf.map_fn(_decode_png_mask, masks, dtype=tf.float32),
        lambda: tf.zeros([0, height, width], dtype=tf.float32)) 
開發者ID:JunweiLiang,項目名稱:Object_Detection_Tracking,代碼行數:18,代碼來源:tf_example_decoder.py

示例11: parse

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def parse(data_dict):
  """Parse dataset from _data_gen into the same format as sst_binary."""
  sentiment = data_dict['label']
  sentence = data_dict['sentence']
  dense_chars = tf.decode_raw(sentence, tf.uint8)
  dense_chars.set_shape((None,))
  chars = tfp.math.dense_to_sparse(dense_chars)
  if six.PY3:
    safe_chr = lambda c: '?' if c >= 128 else chr(c)
  else:
    safe_chr = chr
  to_char = np.vectorize(safe_chr)
  chars = tf.SparseTensor(indices=chars.indices,
                          values=tf.py_func(to_char, [chars.values], tf.string),
                          dense_shape=chars.dense_shape)
  return {'sentiment': sentiment,
          'sentence': chars} 
開發者ID:deepmind,項目名稱:interval-bound-propagation,代碼行數:19,代碼來源:robust_model.py

示例12: _transform_in_feature_specification

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def _transform_in_feature_specification(
      self, tensor_spec_struct
  ):
    """The specification for the input features for the preprocess_fn.

    Here we will transform the feature spec to represent the requirements
    for preprocessing.

    Args:
      tensor_spec_struct: A flat spec structure {str: TensorSpec}.

    Returns:
      tensor_spec_struct: The transformed flat spec structure {str:
      TensorSpec}.
    """
    self.update_spec(
        tensor_spec_struct,
        'state/image',
        shape=(512, 640, 3),
        dtype=tf.uint8,
        data_format='jpeg')
    return tensor_spec_struct 
開發者ID:google-research,項目名稱:tensor2robot,代碼行數:24,代碼來源:t2r_models.py

示例13: test_pad_image_tensor_to_spec_shape

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def test_pad_image_tensor_to_spec_shape(self):
    varlen_spec = utils.ExtendedTensorSpec(
        shape=(3, 2, 2, 1),
        dtype=tf.uint8,
        name='varlen',
        data_format='png',
        varlen_default_value=3.0)
    test_data = [[
        [[[1]] * 2] * 2,
        [[[2]] * 2] * 2,
    ]]
    prepadded_tensor = tf.convert_to_tensor(test_data, dtype=varlen_spec.dtype)
    tensor = utils.pad_or_clip_tensor_to_spec_shape(prepadded_tensor,
                                                    varlen_spec)
    with self.session() as sess:
      np_tensor = sess.run(tensor)
      self.assertAllEqual(
          np_tensor,
          np.array([[
              [[[1]] * 2] * 2,
              [[[2]] * 2] * 2,
              [[[3]] * 2] * 2,
          ]])) 
開發者ID:google-research,項目名稱:tensor2robot,代碼行數:25,代碼來源:tensorspec_utils_test.py

示例14: neglogp

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def neglogp(self, x):
        """
        return tf.nn.sparse_softmax_cross_entropy_with_logits(logits=self.logits, labels=x)
        Note: we can't use sparse_softmax_cross_entropy_with_logits because
              the implementation does not allow second-order derivatives...
        """
        if x.dtype in {tf.uint8, tf.int32, tf.int64}:
            # one-hot encoding
            x_shape_list = x.shape.as_list()
            logits_shape_list = self.logits.get_shape().as_list()[:-1]
            for xs, ls in zip(x_shape_list, logits_shape_list):
                if xs is not None and ls is not None:
                    assert xs == ls, 'shape mismatch: {} in x vs {} in logits'.format(xs, ls)

            x = tf.one_hot(x, self.logits.get_shape().as_list()[-1])
        else:
            # already encoded
            assert x.shape.as_list() == self.logits.shape.as_list()

        return tf.nn.softmax_cross_entropy_with_logits_v2(
            logits=self.logits,
            labels=x) 
開發者ID:microsoft,項目名稱:nni,代碼行數:24,代碼來源:distri.py

示例15: serve_images

# 需要導入模塊: from tensorflow.compat import v1 [as 別名]
# 或者: from tensorflow.compat.v1 import uint8 [as 別名]
def serve_images(self, image_arrays):
    """Serve a list of image arrays.

    Args:
      image_arrays: A list of image content with each image has shape [height,
        width, 3] and uint8 type.

    Returns:
      A list of detections.
    """
    if not self.sess:
      self.build()
    predictions = self.sess.run(
        self.signitures['prediction'],
        feed_dict={self.signitures['image_arrays']: image_arrays})
    return predictions 
開發者ID:PINTO0309,項目名稱:PINTO_model_zoo,代碼行數:18,代碼來源:inference.py


注:本文中的tensorflow.compat.v1.uint8方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。