doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
tf.identity View source on GitHub Return a Tensor with the same shape and contents as input. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.identity
tf.identity(
input, name=None
)
The return value is not the same Tensor as the original, but contains the same values. This operation is fast when used on the same device. For example:
a = tf.constant([0.78])
a_identity = tf.identity(a)
a.numpy()
array([0.78], dtype=float32)
a_identity.numpy()
array([0.78], dtype=float32)
Calling tf.identity on a variable will make a Tensor that represents the value of that variable at the time it is called. This is equivalent to calling <variable>.read_value().
a = tf.Variable(5)
a_identity = tf.identity(a)
a.assign_add(1)
<tf.Variable ... shape=() dtype=int32, numpy=6>
a.numpy()
6
a_identity.numpy()
5
Args
input A Tensor.
name A name for the operation (optional).
Returns A Tensor. Has the same type as input. | tensorflow.identity |
tf.identity_n Returns a list of tensors with the same shapes and contents as the input View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.identity_n
tf.identity_n(
input, name=None
)
tensors. This op can be used to override the gradient for complicated functions. For example, suppose y = f(x) and we wish to apply a custom function g for backprop such that dx = g(dy). In Python, with tf.get_default_graph().gradient_override_map(
{'IdentityN': 'OverrideGradientWithG'}):
y, _ = identity_n([f(x), x])
@tf.RegisterGradient('OverrideGradientWithG')
def ApplyG(op, dy, _):
return [None, g(dy)] # Do not backprop to f(x).
Args
input A list of Tensor objects.
name A name for the operation (optional).
Returns A list of Tensor objects. Has the same type as input. | tensorflow.identity_n |
Module: tf.image Image ops. The tf.image module contains various functions for image processing and decoding-encoding Ops. Many of the encoding/decoding functions are also available in the core tf.io module. Image processing Resizing The resizing Ops accept input images as tensors of several types. They always output resized images as float32 tensors. The convenience function tf.image.resize supports both 4-D and 3-D tensors as input and output. 4-D tensors are for batches of images, 3-D tensors for individual images. Resized images will be distorted if their original aspect ratio is not the same as size. To avoid distortions see tf.image.resize_with_pad. tf.image.resize tf.image.resize_with_pad tf.image.resize_with_crop_or_pad The Class tf.image.ResizeMethod provides various resize methods like bilinear, nearest_neighbor. Converting Between Colorspaces Image ops work either on individual images or on batches of images, depending on the shape of their input Tensor. If 3-D, the shape is [height, width, channels], and the Tensor represents one image. If 4-D, the shape is [batch_size, height, width, channels], and the Tensor represents batch_size images. Currently, channels can usefully be 1, 2, 3, or 4. Single-channel images are grayscale, images with 3 channels are encoded as either RGB or HSV. Images with 2 or 4 channels include an alpha channel, which has to be stripped from the image before passing the image to most image processing functions (and can be re-attached later). Internally, images are either stored in as one float32 per channel per pixel (implicitly, values are assumed to lie in [0,1)) or one uint8 per channel per pixel (values are assumed to lie in [0,255]). TensorFlow can convert between images in RGB or HSV or YIQ.
tf.image.rgb_to_grayscale, tf.image.grayscale_to_rgb
tf.image.rgb_to_hsv, tf.image.hsv_to_rgb
tf.image.rgb_to_yiq, tf.image.yiq_to_rgb
tf.image.rgb_to_yuv, tf.image.yuv_to_rgb
tf.image.image_gradients tf.image.convert_image_dtype Image Adjustments TensorFlow provides functions to adjust images in various ways: brightness, contrast, hue, and saturation. Each adjustment can be done with predefined parameters or with random parameters picked from predefined intervals. Random adjustments are often useful to expand a training set and reduce overfitting. If several adjustments are chained it is advisable to minimize the number of redundant conversions by first converting the images to the most natural data type and representation. tf.image.adjust_brightness tf.image.adjust_contrast tf.image.adjust_gamma tf.image.adjust_hue tf.image.adjust_jpeg_quality tf.image.adjust_saturation tf.image.random_brightness tf.image.random_contrast tf.image.random_hue tf.image.random_saturation tf.image.per_image_standardization Working with Bounding Boxes tf.image.draw_bounding_boxes tf.image.combined_non_max_suppression tf.image.generate_bounding_box_proposals tf.image.non_max_suppression tf.image.non_max_suppression_overlaps tf.image.non_max_suppression_padded tf.image.non_max_suppression_with_scores tf.image.pad_to_bounding_box tf.image.sample_distorted_bounding_box Cropping tf.image.central_crop tf.image.crop_and_resize tf.image.crop_to_bounding_box tf.io.decode_and_crop_jpeg tf.image.extract_glimpse tf.image.random_crop tf.image.resize_with_crop_or_pad Flipping, Rotating and Transposing tf.image.flip_left_right tf.image.flip_up_down tf.image.random_flip_left_right tf.image.random_flip_up_down tf.image.rot90 tf.image.transpose Image decoding and encoding TensorFlow provides Ops to decode and encode JPEG and PNG formats. Encoded images are represented by scalar string Tensors, decoded images by 3-D uint8 tensors of shape [height, width, channels]. (PNG also supports uint16.)
Note: decode_gif returns a 4-D array [num_frames, height, width, 3]
The encode and decode Ops apply to one image at a time. Their input and output are all of variable size. If you need fixed size images, pass the output of the decode Ops to one of the cropping and resizing Ops. tf.io.decode_bmp tf.io.decode_gif tf.io.decode_image tf.io.decode_jpeg tf.io.decode_and_crop_jpeg tf.io.decode_png tf.io.encode_jpeg tf.io.encode_png Classes class ResizeMethod: See tf.image.resize for details. Functions adjust_brightness(...): Adjust the brightness of RGB or Grayscale images. adjust_contrast(...): Adjust contrast of RGB or grayscale images. adjust_gamma(...): Performs Gamma Correction. adjust_hue(...): Adjust hue of RGB images. adjust_jpeg_quality(...): Adjust jpeg encoding quality of an image. adjust_saturation(...): Adjust saturation of RGB images. central_crop(...): Crop the central region of the image(s). combined_non_max_suppression(...): Greedily selects a subset of bounding boxes in descending order of score. convert_image_dtype(...): Convert image to dtype, scaling its values if needed. crop_and_resize(...): Extracts crops from the input image tensor and resizes them. crop_to_bounding_box(...): Crops an image to a specified bounding box. decode_and_crop_jpeg(...): Decode and Crop a JPEG-encoded image to a uint8 tensor. decode_bmp(...): Decode the first frame of a BMP-encoded image to a uint8 tensor. decode_gif(...): Decode the frame(s) of a GIF-encoded image to a uint8 tensor. decode_image(...): Function for decode_bmp, decode_gif, decode_jpeg, and decode_png. decode_jpeg(...): Decode a JPEG-encoded image to a uint8 tensor. decode_png(...): Decode a PNG-encoded image to a uint8 or uint16 tensor. draw_bounding_boxes(...): Draw bounding boxes on a batch of images. encode_jpeg(...): JPEG-encode an image. encode_png(...): PNG-encode an image. extract_glimpse(...): Extracts a glimpse from the input tensor. extract_jpeg_shape(...): Extract the shape information of a JPEG-encoded image. extract_patches(...): Extract patches from images. flip_left_right(...): Flip an image horizontally (left to right). flip_up_down(...): Flip an image vertically (upside down). generate_bounding_box_proposals(...): Generate bounding box proposals from encoded bounding boxes. grayscale_to_rgb(...): Converts one or more images from Grayscale to RGB. hsv_to_rgb(...): Convert one or more images from HSV to RGB. image_gradients(...): Returns image gradients (dy, dx) for each color channel. is_jpeg(...): Convenience function to check if the 'contents' encodes a JPEG image. non_max_suppression(...): Greedily selects a subset of bounding boxes in descending order of score. non_max_suppression_overlaps(...): Greedily selects a subset of bounding boxes in descending order of score. non_max_suppression_padded(...): Greedily selects a subset of bounding boxes in descending order of score. non_max_suppression_with_scores(...): Greedily selects a subset of bounding boxes in descending order of score. pad_to_bounding_box(...): Pad image with zeros to the specified height and width. per_image_standardization(...): Linearly scales each image in image to have mean 0 and variance 1. psnr(...): Returns the Peak Signal-to-Noise Ratio between a and b. random_brightness(...): Adjust the brightness of images by a random factor. random_contrast(...): Adjust the contrast of an image or images by a random factor. random_crop(...): Randomly crops a tensor to a given size. random_flip_left_right(...): Randomly flip an image horizontally (left to right). random_flip_up_down(...): Randomly flips an image vertically (upside down). random_hue(...): Adjust the hue of RGB images by a random factor. random_jpeg_quality(...): Randomly changes jpeg encoding quality for inducing jpeg noise. random_saturation(...): Adjust the saturation of RGB images by a random factor. resize(...): Resize images to size using the specified method. resize_with_crop_or_pad(...): Crops and/or pads an image to a target width and height. resize_with_pad(...): Resizes and pads an image to a target width and height. rgb_to_grayscale(...): Converts one or more images from RGB to Grayscale. rgb_to_hsv(...): Converts one or more images from RGB to HSV. rgb_to_yiq(...): Converts one or more images from RGB to YIQ. rgb_to_yuv(...): Converts one or more images from RGB to YUV. rot90(...): Rotate image(s) counter-clockwise by 90 degrees. sample_distorted_bounding_box(...): Generate a single randomly distorted bounding box for an image. sobel_edges(...): Returns a tensor holding Sobel edge maps. ssim(...): Computes SSIM index between img1 and img2. ssim_multiscale(...): Computes the MS-SSIM between img1 and img2. stateless_random_brightness(...): Adjust the brightness of images by a random factor deterministically. stateless_random_contrast(...): Adjust the contrast of images by a random factor deterministically. stateless_random_crop(...): Randomly crops a tensor to a given size in a deterministic manner. stateless_random_flip_left_right(...): Randomly flip an image horizontally (left to right) deterministically. stateless_random_flip_up_down(...): Randomly flip an image vertically (upside down) deterministically. stateless_random_hue(...): Adjust the hue of RGB images by a random factor deterministically. stateless_random_jpeg_quality(...): Deterministically radomize jpeg encoding quality for inducing jpeg noise. stateless_random_saturation(...): Adjust the saturation of RGB images by a random factor deterministically. stateless_sample_distorted_bounding_box(...): Generate a randomly distorted bounding box for an image deterministically. total_variation(...): Calculate and return the total variation for one or more images. transpose(...): Transpose image(s) by swapping the height and width dimension. yiq_to_rgb(...): Converts one or more images from YIQ to RGB. yuv_to_rgb(...): Converts one or more images from YUV to RGB. | tensorflow.image |
tf.image.adjust_brightness View source on GitHub Adjust the brightness of RGB or Grayscale images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.adjust_brightness
tf.image.adjust_brightness(
image, delta
)
This is a convenience method that converts RGB images to float representation, adjusts their brightness, and then converts them back to the original data type. If several adjustments are chained, it is advisable to minimize the number of redundant conversions. The value delta is added to all components of the tensor image. image is converted to float and scaled appropriately if it is in fixed-point representation, and delta is converted to the same data type. For regular images, delta should be in the range (-1,1), as it is added to the image in floating point representation, where pixel values are in the [0,1) range. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.adjust_brightness(x, delta=0.1)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 1.1, 2.1, 3.1],
[ 4.1, 5.1, 6.1]],
[[ 7.1, 8.1, 9.1],
[10.1, 11.1, 12.1]]], dtype=float32)>
Args
image RGB image or images to adjust.
delta A scalar. Amount to add to the pixel values.
Returns A brightness-adjusted tensor of the same shape and type as image. | tensorflow.image.adjust_brightness |
tf.image.adjust_contrast View source on GitHub Adjust contrast of RGB or grayscale images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.adjust_contrast
tf.image.adjust_contrast(
images, contrast_factor
)
This is a convenience method that converts RGB images to float representation, adjusts their contrast, and then converts them back to the original data type. If several adjustments are chained, it is advisable to minimize the number of redundant conversions. images is a tensor of at least 3 dimensions. The last 3 dimensions are interpreted as [height, width, channels]. The other dimensions only represent a collection of images, such as [batch, height, width, channels]. Contrast is adjusted independently for each channel of each image. For each channel, this Op computes the mean of the image pixels in the channel and then adjusts each component x of each pixel to (x - mean) * contrast_factor + mean. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.adjust_contrast(x, 2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[-3.5, -2.5, -1.5],
[ 2.5, 3.5, 4.5]],
[[ 8.5, 9.5, 10.5],
[14.5, 15.5, 16.5]]], dtype=float32)>
Args
images Images to adjust. At least 3-D.
contrast_factor A float multiplier for adjusting contrast.
Returns The contrast-adjusted image or images. | tensorflow.image.adjust_contrast |
tf.image.adjust_gamma View source on GitHub Performs Gamma Correction. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.adjust_gamma
tf.image.adjust_gamma(
image, gamma=1, gain=1
)
on the input image. Also known as Power Law Transform. This function converts the input images at first to float representation, then transforms them pixelwise according to the equation Out = gain * In**gamma, and then converts the back to the original data type. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.adjust_gamma(x, 0.2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[1. , 1.1486983, 1.2457309],
[1.319508 , 1.3797297, 1.4309691]],
[[1.4757731, 1.5157166, 1.5518456],
[1.5848932, 1.6153942, 1.6437519]]], dtype=float32)>
Args
image RGB image or images to adjust.
gamma A scalar or tensor. Non-negative real number.
gain A scalar or tensor. The constant multiplier.
Returns A Tensor. A Gamma-adjusted tensor of the same shape and type as image.
Raises
ValueError If gamma is negative. Notes: For gamma greater than 1, the histogram will shift towards left and the output image will be darker than the input image. For gamma less than 1, the histogram will shift towards right and the output image will be brighter than the input image. References: Wikipedia | tensorflow.image.adjust_gamma |
tf.image.adjust_hue View source on GitHub Adjust hue of RGB images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.adjust_hue
tf.image.adjust_hue(
image, delta, name=None
)
This is a convenience method that converts an RGB image to float representation, converts it to HSV, adds an offset to the hue channel, converts back to RGB and then back to the original data type. If several adjustments are chained it is advisable to minimize the number of redundant conversions. image is an RGB image. The image hue is adjusted by converting the image(s) to HSV and rotating the hue channel (H) by delta. The image is then converted back to RGB. delta must be in the interval [-1, 1]. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.adjust_hue(x, 0.2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 2.3999996, 1. , 3. ],
[ 5.3999996, 4. , 6. ]],
[[ 8.4 , 7. , 9. ],
[11.4 , 10. , 12. ]]], dtype=float32)>
Args
image RGB image or images. The size of the last dimension must be 3.
delta float. How much to add to the hue channel.
name A name for this operation (optional).
Returns Adjusted image(s), same shape and DType as image.
Usage Example:
image = [[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]],
[[13, 14, 15], [16, 17, 18]]]
image = tf.constant(image)
tf.image.adjust_hue(image, 0.2)
<tf.Tensor: shape=(3, 2, 3), dtype=int32, numpy=
array([[[ 2, 1, 3],
[ 5, 4, 6]],
[[ 8, 7, 9],
[11, 10, 12]],
[[14, 13, 15],
[17, 16, 18]]], dtype=int32)> | tensorflow.image.adjust_hue |
tf.image.adjust_jpeg_quality View source on GitHub Adjust jpeg encoding quality of an image. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.adjust_jpeg_quality
tf.image.adjust_jpeg_quality(
image, jpeg_quality, name=None
)
This is a convenience method that converts an image to uint8 representation, encodes it to jpeg with jpeg_quality, decodes it, and then converts back to the original data type. jpeg_quality must be in the interval [0, 100]. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.adjust_jpeg_quality(x, 75)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[1., 1., 1.],
[1., 1., 1.]],
[[1., 1., 1.],
[1., 1., 1.]]], dtype=float32)>
Args
image 3D image. The size of the last dimension must be None, 1 or 3.
jpeg_quality Python int or Tensor of type int32. jpeg encoding quality.
name A name for this operation (optional).
Returns Adjusted image, same shape and DType as image.
Raises
InvalidArgumentError quality must be in [0,100]
InvalidArgumentError image must have 1 or 3 channels | tensorflow.image.adjust_jpeg_quality |
tf.image.adjust_saturation View source on GitHub Adjust saturation of RGB images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.adjust_saturation
tf.image.adjust_saturation(
image, saturation_factor, name=None
)
This is a convenience method that converts RGB images to float representation, converts them to HSV, adds an offset to the saturation channel, converts back to RGB and then back to the original data type. If several adjustments are chained it is advisable to minimize the number of redundant conversions. image is an RGB image or images. The image saturation is adjusted by converting the images to HSV and multiplying the saturation (S) channel by saturation_factor and clipping. The images are then converted back to RGB. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.adjust_saturation(x, 0.5)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 2. , 2.5, 3. ],
[ 5. , 5.5, 6. ]],
[[ 8. , 8.5, 9. ],
[11. , 11.5, 12. ]]], dtype=float32)>
Args
image RGB image or images. The size of the last dimension must be 3.
saturation_factor float. Factor to multiply the saturation by.
name A name for this operation (optional).
Returns Adjusted image(s), same shape and DType as image.
Raises
InvalidArgumentError input must have 3 channels | tensorflow.image.adjust_saturation |
tf.image.central_crop View source on GitHub Crop the central region of the image(s). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.central_crop
tf.image.central_crop(
image, central_fraction
)
Remove the outer parts of an image but retain the central region of the image along each dimension. If we specify central_fraction = 0.5, this function returns the region marked with "X" in the below diagram. --------
| |
| XXXX |
| XXXX |
| | where "X" is the central 50% of the image.
--------
This function works on either a single image (image is a 3-D Tensor), or a batch of images (image is a 4-D Tensor). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]],
[[13.0, 14.0, 15.0],
[16.0, 17.0, 18.0],
[19.0, 20.0, 21.0],
[22.0, 23.0, 24.0]],
[[25.0, 26.0, 27.0],
[28.0, 29.0, 30.0],
[31.0, 32.0, 33.0],
[34.0, 35.0, 36.0]],
[[37.0, 38.0, 39.0],
[40.0, 41.0, 42.0],
[43.0, 44.0, 45.0],
[46.0, 47.0, 48.0]]]
tf.image.central_crop(x, 0.5)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[16., 17., 18.],
[19., 20., 21.]],
[[28., 29., 30.],
[31., 32., 33.]]], dtype=float32)>
Args
image Either a 3-D float Tensor of shape [height, width, depth], or a 4-D Tensor of shape [batch_size, height, width, depth].
central_fraction float (0, 1], fraction of size to crop
Raises
ValueError if central_crop_fraction is not within (0, 1].
Returns 3-D / 4-D float Tensor, as per the input. | tensorflow.image.central_crop |
tf.image.combined_non_max_suppression View source on GitHub Greedily selects a subset of bounding boxes in descending order of score. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.combined_non_max_suppression
tf.image.combined_non_max_suppression(
boxes, scores, max_output_size_per_class, max_total_size, iou_threshold=0.5,
score_threshold=float('-inf'), pad_per_class=False, clip_boxes=True,
name=None
)
This operation performs non_max_suppression on the inputs per batch, across all classes. Prunes away boxes that have high intersection-over-union (IOU) overlap with previously selected boxes. Bounding boxes are supplied as [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm is agnostic to where the origin is in the coordinate system. Also note that this algorithm is invariant to orthogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system result in the same boxes being selected by the algorithm. The output of this operation is the final boxes, scores and classes tensor returned after performing non_max_suppression.
Args
boxes A 4-D float Tensor of shape [batch_size, num_boxes, q, 4]. If q is 1 then same boxes are used for all classes otherwise, if q is equal to number of classes, class-specific boxes are used.
scores A 3-D float Tensor of shape [batch_size, num_boxes, num_classes] representing a single score corresponding to each box (each row of boxes).
max_output_size_per_class A scalar integer Tensor representing the maximum number of boxes to be selected by non-max suppression per class
max_total_size A scalar representing the maximum number of boxes retained over all classes.
iou_threshold A float representing the threshold for deciding whether boxes overlap too much with respect to IOU.
score_threshold A float representing the threshold for deciding when to remove boxes based on score.
pad_per_class If false, the output nmsed boxes, scores and classes are padded/clipped to max_total_size. If true, the output nmsed boxes, scores and classes are padded to be of length max_size_per_class*num_classes, unless it exceeds max_total_size in which case it is clipped to max_total_size. Defaults to false.
clip_boxes If true, the coordinates of output nmsed boxes will be clipped to [0, 1]. If false, output the box coordinates as it is. Defaults to true.
name A name for the operation (optional).
Returns
'nmsed_boxes' A [batch_size, max_detections, 4] float32 tensor containing the non-max suppressed boxes.
'nmsed_scores' A [batch_size, max_detections] float32 tensor containing the scores for the boxes.
'nmsed_classes' A [batch_size, max_detections] float32 tensor containing the class for boxes.
'valid_detections' A [batch_size] int32 tensor indicating the number of valid detections per batch item. Only the top valid_detections[i] entries in nms_boxes[i], nms_scores[i] and nms_class[i] are valid. The rest of the entries are zero paddings. | tensorflow.image.combined_non_max_suppression |
tf.image.convert_image_dtype View source on GitHub Convert image to dtype, scaling its values if needed. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.convert_image_dtype
tf.image.convert_image_dtype(
image, dtype, saturate=False, name=None
)
Images that are represented using floating point values are expected to have values in the range [0,1). Image data stored in integer data types are expected to have values in the range [0,MAX], where MAX is the largest positive representable number for the data type. This op converts between data types, scaling the values appropriately before casting. Note that converting from floating point inputs to integer types may lead to over/underflow problems. Set saturate to True to avoid such problem in problematic conversions. If enabled, saturation will clip the output into the allowed range before performing a potentially dangerous cast (and only before performing such a cast, i.e., when casting from a floating point to an integer type, and when casting from a signed to an unsigned type; saturate has no effect on casts between floats, or on casts that increase the type's range). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.convert_image_dtype(x, dtype=tf.float16, saturate=False)
<tf.Tensor: shape=(2, 2, 3), dtype=float16, numpy=
array([[[ 1., 2., 3.],
[ 4., 5., 6.]],
[[ 7., 8., 9.],
[10., 11., 12.]]], dtype=float16)>
Args
image An image.
dtype A DType to convert image to.
saturate If True, clip the input before casting (if necessary).
name A name for this operation (optional).
Returns image, converted to dtype.
Raises
AttributeError Raises an attribute error when dtype is neither float nor integer | tensorflow.image.convert_image_dtype |
tf.image.crop_and_resize View source on GitHub Extracts crops from the input image tensor and resizes them.
tf.image.crop_and_resize(
image, boxes, box_indices, crop_size, method='bilinear',
extrapolation_value=0, name=None
)
Extracts crops from the input image tensor and resizes them using bilinear sampling or nearest neighbor sampling (possibly with aspect ratio change) to a common output size specified by crop_size. This is more general than the crop_to_bounding_box op which extracts a fixed size slice from the input image and does not allow resizing or aspect ratio change. Returns a tensor with crops from the input image at positions defined at the bounding box locations in boxes. The cropped boxes are all resized (with bilinear or nearest neighbor interpolation) to a fixed size = [crop_height, crop_width]. The result is a 4-D tensor [num_boxes, crop_height, crop_width, depth]. The resizing is corner aligned. In particular, if boxes = [[0, 0, 1, 1]], the method will give identical results to using tf.compat.v1.image.resize_bilinear() or tf.compat.v1.image.resize_nearest_neighbor()(depends on the method argument) with align_corners=True.
Args
image A 4-D tensor of shape [batch, image_height, image_width, depth]. Both image_height and image_width need to be positive.
boxes A 2-D tensor of shape [num_boxes, 4]. The i-th row of the tensor specifies the coordinates of a box in the box_ind[i] image and is specified in normalized coordinates [y1, x1, y2, x2]. A normalized coordinate value of y is mapped to the image coordinate at y * (image_height - 1), so as the [0, 1] interval of normalized image height is mapped to [0, image_height - 1] in image height coordinates. We do allow y1 > y2, in which case the sampled crop is an up-down flipped version of the original image. The width dimension is treated similarly. Normalized coordinates outside the [0, 1] range are allowed, in which case we use extrapolation_value to extrapolate the input image values.
box_indices A 1-D tensor of shape [num_boxes] with int32 values in [0, batch). The value of box_ind[i] specifies the image that the i-th box refers to.
crop_size A 1-D tensor of 2 elements, size = [crop_height, crop_width]. All cropped image patches are resized to this size. The aspect ratio of the image content is not preserved. Both crop_height and crop_width need to be positive.
method An optional string specifying the sampling method for resizing. It can be either "bilinear" or "nearest" and default to "bilinear". Currently two sampling methods are supported: Bilinear and Nearest Neighbor.
extrapolation_value An optional float. Defaults to 0. Value used for extrapolation, when applicable.
name A name for the operation (optional).
Returns A 4-D tensor of shape [num_boxes, crop_height, crop_width, depth].
Example: import tensorflow as tf
BATCH_SIZE = 1
NUM_BOXES = 5
IMAGE_HEIGHT = 256
IMAGE_WIDTH = 256
CHANNELS = 3
CROP_SIZE = (24, 24)
image = tf.random.normal(shape=(BATCH_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH,
CHANNELS) )
boxes = tf.random.uniform(shape=(NUM_BOXES, 4))
box_indices = tf.random.uniform(shape=(NUM_BOXES,), minval=0,
maxval=BATCH_SIZE, dtype=tf.int32)
output = tf.image.crop_and_resize(image, boxes, box_indices, CROP_SIZE)
output.shape #=> (5, 24, 24, 3) | tensorflow.image.crop_and_resize |
tf.image.crop_to_bounding_box View source on GitHub Crops an image to a specified bounding box. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.crop_to_bounding_box
tf.image.crop_to_bounding_box(
image, offset_height, offset_width, target_height, target_width
)
This op cuts a rectangular part out of image. The top-left corner of the returned image is at offset_height, offset_width in image, and its lower-right corner is at offset_height + target_height, offset_width + target_width.
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
offset_height Vertical coordinate of the top-left corner of the result in the input.
offset_width Horizontal coordinate of the top-left corner of the result in the input.
target_height Height of the result.
target_width Width of the result.
Returns If image was 4-D, a 4-D float Tensor of shape [batch, target_height, target_width, channels] If image was 3-D, a 3-D float Tensor of shape [target_height, target_width, channels]
Raises
ValueError If the shape of image is incompatible with the offset_* or target_* arguments, or either offset_height or offset_width is negative, or either target_height or target_width is not positive. | tensorflow.image.crop_to_bounding_box |
tf.image.draw_bounding_boxes View source on GitHub Draw bounding boxes on a batch of images.
tf.image.draw_bounding_boxes(
images, boxes, colors, name=None
)
Outputs a copy of images but draws on top of the pixels zero or more bounding boxes specified by the locations in boxes. The coordinates of the each bounding box in boxes are encoded as [y_min, x_min, y_max, x_max]. The bounding box coordinates are floats in [0.0, 1.0] relative to the width and the height of the underlying image. For example, if an image is 100 x 200 pixels (height x width) and the bounding box is [0.1, 0.2, 0.5, 0.9], the upper-left and bottom-right coordinates of the bounding box will be (40, 10) to (180, 50) (in (x,y) coordinates). Parts of the bounding box may fall outside the image.
Args
images A Tensor. Must be one of the following types: float32, half. 4-D with shape [batch, height, width, depth]. A batch of images.
boxes A Tensor of type float32. 3-D with shape [batch, num_bounding_boxes, 4] containing bounding boxes.
colors A Tensor of type float32. 2-D. A list of RGBA colors to cycle through for the boxes.
name A name for the operation (optional).
Returns A Tensor. Has the same type as images.
Usage Example:
# create an empty image
img = tf.zeros([1, 3, 3, 3])
# draw a box around the image
box = np.array([0, 0, 1, 1])
boxes = box.reshape([1, 1, 4])
# alternate between red and blue
colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
tf.image.draw_bounding_boxes(img, boxes, colors)
<tf.Tensor: shape=(1, 3, 3, 3), dtype=float32, numpy=
array([[[[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]],
[[1., 0., 0.],
[0., 0., 0.],
[1., 0., 0.]],
[[1., 0., 0.],
[1., 0., 0.],
[1., 0., 0.]]]], dtype=float32)> | tensorflow.image.draw_bounding_boxes |
tf.image.extract_glimpse View source on GitHub Extracts a glimpse from the input tensor.
tf.image.extract_glimpse(
input, size, offsets, centered=True, normalized=True, noise='uniform',
name=None
)
Returns a set of windows called glimpses extracted at location offsets from the input tensor. If the windows only partially overlaps the inputs, the non-overlapping areas will be filled with random noise. The result is a 4-D tensor of shape [batch_size, glimpse_height, glimpse_width, channels]. The channels and batch dimensions are the same as that of the input tensor. The height and width of the output windows are specified in the size parameter. The argument normalized and centered controls how the windows are built: If the coordinates are normalized but not centered, 0.0 and 1.0 correspond to the minimum and maximum of each height and width dimension. If the coordinates are both normalized and centered, they range from -1.0 to 1.0. The coordinates (-1.0, -1.0) correspond to the upper left corner, the lower right corner is located at (1.0, 1.0) and the center is at (0, 0). If the coordinates are not normalized they are interpreted as numbers of pixels. Usage Example:
x = [[[[0.0],
[1.0],
[2.0]],
[[3.0],
[4.0],
[5.0]],
[[6.0],
[7.0],
[8.0]]]]
tf.image.extract_glimpse(x, size=(2, 2), offsets=[[1, 1]],
centered=False, normalized=False)
<tf.Tensor: shape=(1, 2, 2, 1), dtype=float32, numpy=
array([[[[4.],
[5.]],
[[7.],
[8.]]]], dtype=float32)>
Args
input A Tensor of type float32. A 4-D float tensor of shape [batch_size, height, width, channels].
size A Tensor of type int32. A 1-D tensor of 2 elements containing the size of the glimpses to extract. The glimpse height must be specified first, following by the glimpse width.
offsets A Tensor of type float32. A 2-D integer tensor of shape [batch_size, 2] containing the y, x locations of the center of each window.
centered An optional bool. Defaults to True. indicates if the offset coordinates are centered relative to the image, in which case the (0, 0) offset is relative to the center of the input images. If false, the (0,0) offset corresponds to the upper left corner of the input images.
normalized An optional bool. Defaults to True. indicates if the offset coordinates are normalized.
noise An optional string. Defaults to uniform. indicates if the noise should be uniform (uniform distribution), gaussian (gaussian distribution), or zero (zero padding).
name A name for the operation (optional).
Returns A Tensor of type float32. | tensorflow.image.extract_glimpse |
tf.image.extract_patches View source on GitHub Extract patches from images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.extract_patches
tf.image.extract_patches(
images, sizes, strides, rates, padding, name=None
)
This op collects patches from the input image, as if applying a convolution. All extracted patches are stacked in the depth (last) dimension of the output. Specifically, the op extracts patches of shape sizes which are strides apart in the input image. The output is subsampled using the rates argument, in the same manner as "atrous" or "dilated" convolutions. The result is a 4D tensor which is indexed by batch, row, and column. output[i, x, y] contains a flattened patch of size sizes[1], sizes[2] which is taken from the input starting at images[i, x*strides[1], y*strides[2]]. Each output patch can be reshaped to sizes[1], sizes[2], depth, where depth is images.shape[3]. The output elements are taken from the input at intervals given by the rate argument, as in dilated convolutions. The padding argument has no effect on the size of each patch, it determines how many patches are extracted. If VALID, only patches which are fully contained in the input image are included. If SAME, all patches whose starting point is inside the input are included, and areas outside the input default to zero. Example: n = 10
# images is a 1 x 10 x 10 x 1 array that contains the numbers 1 through 100
images = [[[[x * n + y + 1] for y in range(n)] for x in range(n)]]
# We generate two outputs as follows:
# 1. 3x3 patches with stride length 5
# 2. Same as above, but the rate is increased to 2
tf.image.extract_patches(images=images,
sizes=[1, 3, 3, 1],
strides=[1, 5, 5, 1],
rates=[1, 1, 1, 1],
padding='VALID')
# Yields:
[[[[ 1 2 3 11 12 13 21 22 23]
[ 6 7 8 16 17 18 26 27 28]]
[[51 52 53 61 62 63 71 72 73]
[56 57 58 66 67 68 76 77 78]]]]
If we mark the pixels in the input image which are taken for the output with *, we see the pattern:
* * * 4 5 * * * 9 10
* * * 14 15 * * * 19 20
* * * 24 25 * * * 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
* * * 54 55 * * * 59 60
* * * 64 65 * * * 69 70
* * * 74 75 * * * 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
tf.image.extract_patches(images=images,
sizes=[1, 3, 3, 1],
strides=[1, 5, 5, 1],
rates=[1, 2, 2, 1],
padding='VALID')
# Yields:
[[[[ 1 3 5 21 23 25 41 43 45]
[ 6 8 10 26 28 30 46 48 50]]
[[ 51 53 55 71 73 75 91 93 95]
[ 56 58 60 76 78 80 96 98 100]]]]
We can again draw the effect, this time using the symbols *, x, + and o to distinguish the patches:
* 2 * 4 * x 7 x 9 x
11 12 13 14 15 16 17 18 19 20
* 22 * 24 * x 27 x 29 x
31 32 33 34 35 36 37 38 39 40
* 42 * 44 * x 47 x 49 x
+ 52 + 54 + o 57 o 59 o
61 62 63 64 65 66 67 68 69 70
+ 72 + 74 + o 77 o 79 o
81 82 83 84 85 86 87 88 89 90
+ 92 + 94 + o 97 o 99 o
Args
images A 4-D Tensor with shape [batch, in_rows, in_cols, depth].
sizes The size of the extracted patches. Must be [1, size_rows, size_cols, 1].
strides A 1-D Tensor of length 4. How far the centers of two consecutive patches are in the images. Must be: [1, stride_rows, stride_cols, 1].
rates A 1-D Tensor of length 4. Must be: [1, rate_rows, rate_cols, 1]. This is the input stride, specifying how far two consecutive patch samples are in the input. Equivalent to extracting patches with patch_sizes_eff = patch_sizes + (patch_sizes - 1) * (rates - 1), followed by subsampling them spatially by a factor of rates. This is equivalent to rate in dilated (a.k.a. Atrous) convolutions.
padding The type of padding algorithm to use.
name A name for the operation (optional).
Returns A 4-D Tensor of the same type as the input. | tensorflow.image.extract_patches |
tf.image.flip_left_right View source on GitHub Flip an image horizontally (left to right). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.flip_left_right
tf.image.flip_left_right(
image
)
Outputs the contents of image flipped along the width dimension. See also tf.reverse. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.flip_left_right(x)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 4., 5., 6.],
[ 1., 2., 3.]],
[[10., 11., 12.],
[ 7., 8., 9.]]], dtype=float32)>
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
Returns A tensor of the same type and shape as image.
Raises
ValueError if the shape of image not supported. | tensorflow.image.flip_left_right |
tf.image.flip_up_down View source on GitHub Flip an image vertically (upside down). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.flip_up_down
tf.image.flip_up_down(
image
)
Outputs the contents of image flipped along the height dimension. See also reverse(). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.flip_up_down(x)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 7., 8., 9.],
[10., 11., 12.]],
[[ 1., 2., 3.],
[ 4., 5., 6.]]], dtype=float32)>
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
Returns A Tensor of the same type and shape as image.
Raises
ValueError if the shape of image not supported. | tensorflow.image.flip_up_down |
tf.image.generate_bounding_box_proposals Generate bounding box proposals from encoded bounding boxes. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.generate_bounding_box_proposals
tf.image.generate_bounding_box_proposals(
scores, bbox_deltas, image_info, anchors, nms_threshold=0.7, pre_nms_topn=6000,
min_size=16, post_nms_topn=300, name=None
)
Args
scores A 4-D float Tensor of shape [num_images, height, width, num_achors] containing scores of the boxes for given anchors, can be unsorted.
bbox_deltas A 4-D float Tensor of shape [num_images, height, width, 4 x num_anchors] encoding boxes with respect to each anchor. Coordinates are given in the form [dy, dx, dh, dw].
image_info A 2-D float Tensor of shape [num_images, 5] containing image information Height, Width, Scale.
anchors A 2-D float Tensor of shape [num_anchors, 4] describing the anchor boxes. Boxes are formatted in the form [y1, x1, y2, x2].
nms_threshold A scalar float Tensor for non-maximal-suppression threshold. Defaults to 0.7.
pre_nms_topn A scalar int Tensor for the number of top scoring boxes to be used as input. Defaults to 6000.
min_size A scalar float Tensor. Any box that has a smaller size than min_size will be discarded. Defaults to 16.
post_nms_topn An integer. Maximum number of rois in the output.
name A name for this operation (optional).
Returns
rois Region of interest boxes sorted by their scores.
roi_probabilities scores of the ROI boxes in the ROIs' Tensor. | tensorflow.image.generate_bounding_box_proposals |
tf.image.grayscale_to_rgb View source on GitHub Converts one or more images from Grayscale to RGB. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.grayscale_to_rgb
tf.image.grayscale_to_rgb(
images, name=None
)
Outputs a tensor of the same DType and rank as images. The size of the last dimension of the output is 3, containing the RGB value of the pixels. The input images' last dimension must be size 1.
original = tf.constant([[[1.0], [2.0], [3.0]]])
converted = tf.image.grayscale_to_rgb(original)
print(converted.numpy())
[[[1. 1. 1.]
[2. 2. 2.]
[3. 3. 3.]]]
Args
images The Grayscale tensor to convert. The last dimension must be size 1.
name A name for the operation (optional).
Returns The converted grayscale image(s). | tensorflow.image.grayscale_to_rgb |
tf.image.hsv_to_rgb Convert one or more images from HSV to RGB. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.hsv_to_rgb
tf.image.hsv_to_rgb(
images, name=None
)
Outputs a tensor of the same shape as the images tensor, containing the RGB value of the pixels. The output is only well defined if the value in images are in [0,1]. See rgb_to_hsv for a description of the HSV encoding.
Args
images A Tensor. Must be one of the following types: half, bfloat16, float32, float64. 1-D or higher rank. HSV data to convert. Last dimension must be size 3.
name A name for the operation (optional).
Returns A Tensor. Has the same type as images. | tensorflow.image.hsv_to_rgb |
tf.image.image_gradients View source on GitHub Returns image gradients (dy, dx) for each color channel. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.image_gradients
tf.image.image_gradients(
image
)
Both output tensors have the same shape as the input: [batch_size, h, w, d]. The gradient values are organized so that [I(x+1, y) - I(x, y)] is in location (x, y). That means that dy will always have zeros in the last row, and dx will always have zeros in the last column. Usage Example: BATCH_SIZE = 1
IMAGE_HEIGHT = 5
IMAGE_WIDTH = 5
CHANNELS = 1
image = tf.reshape(tf.range(IMAGE_HEIGHT * IMAGE_WIDTH * CHANNELS,
delta=1, dtype=tf.float32),
shape=(BATCH_SIZE, IMAGE_HEIGHT, IMAGE_WIDTH, CHANNELS))
dx, dy = tf.image.image_gradients(image)
print(image[0, :,:,0])
tf.Tensor(
[[ 0. 1. 2. 3. 4.]
[ 5. 6. 7. 8. 9.]
[10. 11. 12. 13. 14.]
[15. 16. 17. 18. 19.]
[20. 21. 22. 23. 24.]], shape=(5, 5), dtype=float32)
print(dx[0, :,:,0])
tf.Tensor(
[[5. 5. 5. 5. 5.]
[5. 5. 5. 5. 5.]
[5. 5. 5. 5. 5.]
[5. 5. 5. 5. 5.]
[0. 0. 0. 0. 0.]], shape=(5, 5), dtype=float32)
print(dy[0, :,:,0])
tf.Tensor(
[[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]
[1. 1. 1. 1. 0.]], shape=(5, 5), dtype=float32)
Arguments
image Tensor with shape [batch_size, h, w, d].
Returns Pair of tensors (dy, dx) holding the vertical and horizontal image gradients (1-step finite difference).
Raises
ValueError If image is not a 4D tensor. | tensorflow.image.image_gradients |
tf.image.non_max_suppression View source on GitHub Greedily selects a subset of bounding boxes in descending order of score. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.non_max_suppression
tf.image.non_max_suppression(
boxes, scores, max_output_size, iou_threshold=0.5,
score_threshold=float('-inf'), name=None
)
Prunes away boxes that have high intersection-over-union (IOU) overlap with previously selected boxes. Bounding boxes are supplied as [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm is agnostic to where the origin is in the coordinate system. Note that this algorithm is invariant to orthogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system result in the same boxes being selected by the algorithm. The output of this operation is a set of integers indexing into the input collection of bounding boxes representing the selected boxes. The bounding box coordinates corresponding to the selected indices can then be obtained using the tf.gather operation. For example: selected_indices = tf.image.non_max_suppression(
boxes, scores, max_output_size, iou_threshold)
selected_boxes = tf.gather(boxes, selected_indices)
Args
boxes A 2-D float Tensor of shape [num_boxes, 4].
scores A 1-D float Tensor of shape [num_boxes] representing a single score corresponding to each box (each row of boxes).
max_output_size A scalar integer Tensor representing the maximum number of boxes to be selected by non-max suppression.
iou_threshold A float representing the threshold for deciding whether boxes overlap too much with respect to IOU.
score_threshold A float representing the threshold for deciding when to remove boxes based on score.
name A name for the operation (optional).
Returns
selected_indices A 1-D integer Tensor of shape [M] representing the selected indices from the boxes tensor, where M <= max_output_size. | tensorflow.image.non_max_suppression |
tf.image.non_max_suppression_overlaps View source on GitHub Greedily selects a subset of bounding boxes in descending order of score. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.non_max_suppression_overlaps
tf.image.non_max_suppression_overlaps(
overlaps, scores, max_output_size, overlap_threshold=0.5,
score_threshold=float('-inf'), name=None
)
Prunes away boxes that have high overlap with previously selected boxes. N-by-n overlap values are supplied as square matrix. The output of this operation is a set of integers indexing into the input collection of bounding boxes representing the selected boxes. The bounding box coordinates corresponding to the selected indices can then be obtained using the tf.gather operation. For example: selected_indices = tf.image.non_max_suppression_overlaps(
overlaps, scores, max_output_size, iou_threshold)
selected_boxes = tf.gather(boxes, selected_indices)
Args
overlaps A 2-D float Tensor of shape [num_boxes, num_boxes].
scores A 1-D float Tensor of shape [num_boxes] representing a single score corresponding to each box (each row of boxes).
max_output_size A scalar integer Tensor representing the maximum number of boxes to be selected by non-max suppression.
overlap_threshold A float representing the threshold for deciding whether boxes overlap too much with respect to the provided overlap values.
score_threshold A float representing the threshold for deciding when to remove boxes based on score.
name A name for the operation (optional).
Returns
selected_indices A 1-D integer Tensor of shape [M] representing the selected indices from the overlaps tensor, where M <= max_output_size. | tensorflow.image.non_max_suppression_overlaps |
tf.image.non_max_suppression_padded View source on GitHub Greedily selects a subset of bounding boxes in descending order of score. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.non_max_suppression_padded
tf.image.non_max_suppression_padded(
boxes, scores, max_output_size, iou_threshold=0.5,
score_threshold=float('-inf'), pad_to_max_output_size=False,
name=None, sorted_input=False, canonicalized_coordinates=False, tile_size=512
)
Performs algorithmically equivalent operation to tf.image.non_max_suppression, with the addition of an optional parameter which zero-pads the output to be of size max_output_size. The output of this operation is a tuple containing the set of integers indexing into the input collection of bounding boxes representing the selected boxes and the number of valid indices in the index set. The bounding box coordinates corresponding to the selected indices can then be obtained using the tf.slice and tf.gather operations. For example: ```python selected_indices_padded, num_valid = tf.image.non_max_suppression_padded( boxes, scores, max_output_size, iou_threshold, score_threshold, pad_to_max_output_size=True) selected_indices = tf.slice( selected_indices_padded, tf.constant([0]), num_valid) selected_boxes = tf.gather(boxes, selected_indices)
Args
boxes a tensor of rank 2 or higher with a shape of [..., num_boxes, 4]. Dimensions except the last two are batch dimensions.
scores a tensor of rank 1 or higher with a shape of [..., num_boxes].
max_output_size a scalar integer Tensor representing the maximum number of boxes to be selected by non max suppression.
iou_threshold a float representing the threshold for deciding whether boxes overlap too much with respect to IoU (intersection over union).
score_threshold a float representing the threshold for box scores. Boxes with a score that is not larger than this threshold will be suppressed.
pad_to_max_output_size whether to pad the output idx to max_output_size. Must be set to True when the input is a batch of images.
name name of operation.
sorted_input a boolean indicating whether the input boxes and scores are sorted in descending order by the score.
canonicalized_coordinates if box coordinates are given as [y_min, x_min, y_max, x_max], setting to True eliminate redundant computation to canonicalize box coordinates.
tile_size an integer representing the number of boxes in a tile, i.e., the maximum number of boxes per image that can be used to suppress other boxes in parallel; larger tile_size means larger parallelism and potentially more redundant work.
Returns idx: a tensor with a shape of [..., num_boxes] representing the indices selected by non-max suppression. The leading dimensions are the batch dimensions of the input boxes. All numbers are within [0, num_boxes). For each image (i.e., idx[i]), only the first num_valid[i] indices (i.e., idx[i][:num_valid[i]]) are valid. num_valid: a tensor of rank 0 or higher with a shape of [...] representing the number of valid indices in idx. Its dimensions are the batch dimensions of the input boxes. Raises ValueError: When set pad_to_max_output_size to False for batched input. | tensorflow.image.non_max_suppression_padded |
tf.image.non_max_suppression_with_scores View source on GitHub Greedily selects a subset of bounding boxes in descending order of score. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.non_max_suppression_with_scores
tf.image.non_max_suppression_with_scores(
boxes, scores, max_output_size, iou_threshold=0.5,
score_threshold=float('-inf'), soft_nms_sigma=0.0, name=None
)
Prunes away boxes that have high intersection-over-union (IOU) overlap with previously selected boxes. Bounding boxes are supplied as [y1, x1, y2, x2], where (y1, x1) and (y2, x2) are the coordinates of any diagonal pair of box corners and the coordinates can be provided as normalized (i.e., lying in the interval [0, 1]) or absolute. Note that this algorithm is agnostic to where the origin is in the coordinate system. Note that this algorithm is invariant to orthogonal transformations and translations of the coordinate system; thus translating or reflections of the coordinate system result in the same boxes being selected by the algorithm. The output of this operation is a set of integers indexing into the input collection of bounding boxes representing the selected boxes. The bounding box coordinates corresponding to the selected indices can then be obtained using the tf.gather operation. For example: selected_indices, selected_scores = tf.image.non_max_suppression_padded(
boxes, scores, max_output_size, iou_threshold=1.0, score_threshold=0.1,
soft_nms_sigma=0.5)
selected_boxes = tf.gather(boxes, selected_indices)
This function generalizes the tf.image.non_max_suppression op by also supporting a Soft-NMS (with Gaussian weighting) mode (c.f. Bodla et al, https://arxiv.org/abs/1704.04503) where boxes reduce the score of other overlapping boxes instead of directly causing them to be pruned. Consequently, in contrast to tf.image.non_max_suppression, tf.image.non_max_suppression_padded returns the new scores of each input box in the second output, selected_scores. To enable this Soft-NMS mode, set the soft_nms_sigma parameter to be larger than 0. When soft_nms_sigma equals 0, the behavior of tf.image.non_max_suppression_padded is identical to that of tf.image.non_max_suppression (except for the extra output) both in function and in running time.
Args
boxes A 2-D float Tensor of shape [num_boxes, 4].
scores A 1-D float Tensor of shape [num_boxes] representing a single score corresponding to each box (each row of boxes).
max_output_size A scalar integer Tensor representing the maximum number of boxes to be selected by non-max suppression.
iou_threshold A float representing the threshold for deciding whether boxes overlap too much with respect to IOU.
score_threshold A float representing the threshold for deciding when to remove boxes based on score.
soft_nms_sigma A scalar float representing the Soft NMS sigma parameter; See Bodla et al, https://arxiv.org/abs/1704.04503). When soft_nms_sigma=0.0 (which is default), we fall back to standard (hard) NMS.
name A name for the operation (optional).
Returns
selected_indices A 1-D integer Tensor of shape [M] representing the selected indices from the boxes tensor, where M <= max_output_size.
selected_scores A 1-D float tensor of shape [M] representing the corresponding scores for each selected box, where M <= max_output_size. Scores only differ from corresponding input scores when using Soft NMS (i.e. when soft_nms_sigma>0) | tensorflow.image.non_max_suppression_with_scores |
tf.image.pad_to_bounding_box View source on GitHub Pad image with zeros to the specified height and width. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.pad_to_bounding_box
tf.image.pad_to_bounding_box(
image, offset_height, offset_width, target_height, target_width
)
Adds offset_height rows of zeros on top, offset_width columns of zeros on the left, and then pads the image on the bottom and right with zeros until it has dimensions target_height, target_width. This op does nothing if offset_* is zero and the image already has size target_height by target_width. Usage Example:
x = [[[1., 2., 3.],
[4., 5., 6.]],
[[7., 8., 9.],
[10., 11., 12.]]]
padded_image = tf.image.pad_to_bounding_box(x, 1, 1, 4, 4)
padded_image
<tf.Tensor: shape=(4, 4, 3), dtype=float32, numpy=
array([[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 1., 2., 3.],
[ 4., 5., 6.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 7., 8., 9.],
[10., 11., 12.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]], dtype=float32)>
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
offset_height Number of rows of zeros to add on top.
offset_width Number of columns of zeros to add on the left.
target_height Height of output image.
target_width Width of output image.
Returns If image was 4-D, a 4-D float Tensor of shape [batch, target_height, target_width, channels] If image was 3-D, a 3-D float Tensor of shape [target_height, target_width, channels]
Raises
ValueError If the shape of image is incompatible with the offset_* or target_* arguments, or either offset_height or offset_width is negative. | tensorflow.image.pad_to_bounding_box |
tf.image.per_image_standardization View source on GitHub Linearly scales each image in image to have mean 0 and variance 1. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.per_image_standardization
tf.image.per_image_standardization(
image
)
For each 3-D image x in image, computes (x - mean) / adjusted_stddev, where
mean is the average of all values in x
adjusted_stddev = max(stddev, 1.0/sqrt(N)) is capped away from 0 to protect against division by 0 when handling uniform images
N is the number of elements in x
stddev is the standard deviation of all values in x
Args
image An n-D Tensor with at least 3 dimensions, the last 3 of which are the dimensions of each image.
Returns A Tensor with the same shape and dtype as image.
Raises
ValueError if the shape of 'image' is incompatible with this function. | tensorflow.image.per_image_standardization |
tf.image.psnr View source on GitHub Returns the Peak Signal-to-Noise Ratio between a and b. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.psnr
tf.image.psnr(
a, b, max_val, name=None
)
This is intended to be used on signals (or images). Produces a PSNR value for each image in batch. The last three dimensions of input are expected to be [height, width, depth]. Example: # Read images from file.
im1 = tf.decode_png('path/to/im1.png')
im2 = tf.decode_png('path/to/im2.png')
# Compute PSNR over tf.uint8 Tensors.
psnr1 = tf.image.psnr(im1, im2, max_val=255)
# Compute PSNR over tf.float32 Tensors.
im1 = tf.image.convert_image_dtype(im1, tf.float32)
im2 = tf.image.convert_image_dtype(im2, tf.float32)
psnr2 = tf.image.psnr(im1, im2, max_val=1.0)
# psnr1 and psnr2 both have type tf.float32 and are almost equal.
Arguments
a First set of images.
b Second set of images.
max_val The dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values).
name Namespace to embed the computation in.
Returns The scalar PSNR between a and b. The returned tensor has type tf.float32 and shape [batch_size, 1]. | tensorflow.image.psnr |
tf.image.random_brightness View source on GitHub Adjust the brightness of images by a random factor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_brightness
tf.image.random_brightness(
image, max_delta, seed=None
)
Equivalent to adjust_brightness() using a delta randomly picked in the interval [-max_delta, max_delta).
Args
image An image or images to adjust.
max_delta float, must be non-negative.
seed A Python integer. Used to create a random seed. See tf.compat.v1.set_random_seed for behavior. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.random_brightness(x, 0.2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=...>
Returns The brightness-adjusted image(s).
Raises
ValueError if max_delta is negative. | tensorflow.image.random_brightness |
tf.image.random_contrast View source on GitHub Adjust the contrast of an image or images by a random factor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_contrast
tf.image.random_contrast(
image, lower, upper, seed=None
)
Equivalent to adjust_contrast() but uses a contrast_factor randomly picked in the interval [lower, upper).
Args
image An image tensor with 3 or more dimensions.
lower float. Lower bound for the random contrast factor.
upper float. Upper bound for the random contrast factor.
seed A Python integer. Used to create a random seed. See tf.compat.v1.set_random_seed for behavior. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.random_contrast(x, 0.2, 0.5)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=...>
Returns The contrast-adjusted image(s).
Raises
ValueError if upper <= lower or if lower < 0. | tensorflow.image.random_contrast |
tf.image.random_crop View source on GitHub Randomly crops a tensor to a given size. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_crop, tf.compat.v1.random_crop
tf.image.random_crop(
value, size, seed=None, name=None
)
Slices a shape size portion out of value at a uniformly chosen offset. Requires value.shape >= size. If a dimension should not be cropped, pass the full size of that dimension. For example, RGB images can be cropped with size = [crop_height, crop_width, 3].
Args
value Input tensor to crop.
size 1-D tensor with size the rank of value.
seed Python integer. Used to create a random seed. See tf.random.set_seed for behavior.
name A name for this operation (optional).
Returns A cropped tensor of the same rank as value and shape size. | tensorflow.image.random_crop |
tf.image.random_flip_left_right View source on GitHub Randomly flip an image horizontally (left to right). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_flip_left_right
tf.image.random_flip_left_right(
image, seed=None
)
With a 1 in 2 chance, outputs the contents of image flipped along the second dimension, which is width. Otherwise output the image as-is. When passing a batch of images, each image will be randomly flipped independent of other images. Example usage:
image = np.array([[[1], [2]], [[3], [4]]])
tf.image.random_flip_left_right(image, 5).numpy().tolist()
[[[2], [1]], [[4], [3]]]
Randomly flip multiple images.
images = np.array(
[
[[[1], [2]], [[3], [4]]],
[[[5], [6]], [[7], [8]]]
])
tf.image.random_flip_left_right(images, 6).numpy().tolist()
[[[[2], [1]], [[4], [3]]], [[[5], [6]], [[7], [8]]]]
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
seed A Python integer. Used to create a random seed. See tf.compat.v1.set_random_seed for behavior.
Returns A tensor of the same type and shape as image.
Raises
ValueError if the shape of image not supported. | tensorflow.image.random_flip_left_right |
tf.image.random_flip_up_down View source on GitHub Randomly flips an image vertically (upside down). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_flip_up_down
tf.image.random_flip_up_down(
image, seed=None
)
With a 1 in 2 chance, outputs the contents of image flipped along the first dimension, which is height. Otherwise, output the image as-is. When passing a batch of images, each image will be randomly flipped independent of other images. Example usage:
image = np.array([[[1], [2]], [[3], [4]]])
tf.image.random_flip_up_down(image, 3).numpy().tolist()
[[[3], [4]], [[1], [2]]]
Randomly flip multiple images.
images = np.array(
[
[[[1], [2]], [[3], [4]]],
[[[5], [6]], [[7], [8]]]
])
tf.image.random_flip_up_down(images, 4).numpy().tolist()
[[[[3], [4]], [[1], [2]]], [[[5], [6]], [[7], [8]]]]
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
seed A Python integer. Used to create a random seed. See tf.compat.v1.set_random_seed for behavior.
Returns A tensor of the same type and shape as image.
Raises
ValueError if the shape of image not supported. | tensorflow.image.random_flip_up_down |
tf.image.random_hue View source on GitHub Adjust the hue of RGB images by a random factor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_hue
tf.image.random_hue(
image, max_delta, seed=None
)
Equivalent to adjust_hue() but uses a delta randomly picked in the interval [-max_delta, max_delta). max_delta must be in the interval [0, 0.5]. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.random_hue(x, 0.2)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=...>
Args
image RGB image or images. The size of the last dimension must be 3.
max_delta float. The maximum value for the random delta.
seed An operation-specific seed. It will be used in conjunction with the graph-level seed to determine the real seeds that will be used in this operation. Please see the documentation of set_random_seed for its interaction with the graph-level random seed.
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if max_delta is invalid. | tensorflow.image.random_hue |
tf.image.random_jpeg_quality View source on GitHub Randomly changes jpeg encoding quality for inducing jpeg noise. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_jpeg_quality
tf.image.random_jpeg_quality(
image, min_jpeg_quality, max_jpeg_quality, seed=None
)
min_jpeg_quality must be in the interval [0, 100] and less than max_jpeg_quality. max_jpeg_quality must be in the interval [0, 100]. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.random_jpeg_quality(x, 75, 95)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=...>
Args
image 3D image. Size of the last dimension must be 1 or 3.
min_jpeg_quality Minimum jpeg encoding quality to use.
max_jpeg_quality Maximum jpeg encoding quality to use.
seed An operation-specific seed. It will be used in conjunction with the graph-level seed to determine the real seeds that will be used in this operation. Please see the documentation of set_random_seed for its interaction with the graph-level random seed.
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if min_jpeg_quality or max_jpeg_quality is invalid. | tensorflow.image.random_jpeg_quality |
tf.image.random_saturation View source on GitHub Adjust the saturation of RGB images by a random factor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.random_saturation
tf.image.random_saturation(
image, lower, upper, seed=None
)
Equivalent to adjust_saturation() but uses a saturation_factor randomly picked in the interval [lower, upper). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.random_saturation(x, 5, 10)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 0. , 1.5, 3. ],
[ 0. , 3. , 6. ]],
[[ 0. , 4.5, 9. ],
[ 0. , 6. , 12. ]]], dtype=float32)>
Args
image RGB image or images. The size of the last dimension must be 3.
lower float. Lower bound for the random saturation factor.
upper float. Upper bound for the random saturation factor.
seed An operation-specific seed. It will be used in conjunction with the graph-level seed to determine the real seeds that will be used in this operation. Please see the documentation of set_random_seed for its interaction with the graph-level random seed.
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if upper <= lower or if lower < 0. | tensorflow.image.random_saturation |
tf.image.resize Resize images to size using the specified method.
tf.image.resize(
images, size, method=ResizeMethod.BILINEAR, preserve_aspect_ratio=False,
antialias=False, name=None
)
Resized images will be distorted if their original aspect ratio is not the same as size. To avoid distortions see tf.image.resize_with_pad.
image = tf.constant([
[1,0,0,0,0],
[0,1,0,0,0],
[0,0,1,0,0],
[0,0,0,1,0],
[0,0,0,0,1],
])
# Add "batch" and "channels" dimensions
image = image[tf.newaxis, ..., tf.newaxis]
image.shape.as_list() # [batch, height, width, channels]
[1, 5, 5, 1]
tf.image.resize(image, [3,5])[0,...,0].numpy()
array([[0.6666667, 0.3333333, 0. , 0. , 0. ],
[0. , 0. , 1. , 0. , 0. ],
[0. , 0. , 0. , 0.3333335, 0.6666665]],
dtype=float32)
It works equally well with a single image instead of a batch of images:
tf.image.resize(image[0], [3,5]).shape.as_list()
[3, 5, 1]
When antialias is true, the sampling filter will anti-alias the input image as well as interpolate. When downsampling an image with anti-aliasing the sampling filter kernel is scaled in order to properly anti-alias the input image signal. antialias has no effect when upsampling an image:
a = tf.image.resize(image, [5,10])
b = tf.image.resize(image, [5,10], antialias=True)
tf.reduce_max(abs(a - b)).numpy()
0.0
The method argument expects an item from the image.ResizeMethod enum, or the string equivalent. The options are:
bilinear: Bilinear interpolation. If antialias is true, becomes a hat/tent filter function with radius 1 when downsampling.
lanczos3: Lanczos kernel with radius 3. High-quality practical filter but may have some ringing, especially on synthetic images.
lanczos5: Lanczos kernel with radius 5. Very-high-quality filter but may have stronger ringing.
bicubic: Cubic interpolant of Keys. Equivalent to Catmull-Rom kernel. Reasonably good quality and faster than Lanczos3Kernel, particularly when upsampling.
gaussian: Gaussian kernel with radius 3, sigma = 1.5 / 3.0.
nearest: Nearest neighbor interpolation. antialias has no effect when used with nearest neighbor interpolation.
area: Anti-aliased resampling with area interpolation. antialias has no effect when used with area interpolation; it always anti-aliases.
mitchellcubic: Mitchell-Netravali Cubic non-interpolating filter. For synthetic images (especially those lacking proper prefiltering), less ringing than Keys cubic kernel but less sharp.
Note: Near image edges the filtering kernel may be partially outside the image boundaries. For these pixels, only input pixels inside the image will be included in the filter sum, and the output value will be appropriately normalized.
The return value has type float32, unless the method is ResizeMethod.NEAREST_NEIGHBOR, then the return dtype is the dtype of images:
nn = tf.image.resize(image, [5,7], method='nearest')
nn[0,...,0].numpy()
array([[1, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 1]], dtype=int32)
With preserve_aspect_ratio=True, the aspect ratio is preserved, so size is the maximum for each dimension:
max_10_20 = tf.image.resize(image, [10,20], preserve_aspect_ratio=True)
max_10_20.shape.as_list()
[1, 10, 10, 1]
Args
images 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
size A 1-D int32 Tensor of 2 elements: new_height, new_width. The new size for the images.
method An image.ResizeMethod, or string equivalent. Defaults to bilinear.
preserve_aspect_ratio Whether to preserve the aspect ratio. If this is set, then images will be resized to a size that fits in size while preserving the aspect ratio of the original image. Scales up the image if size is bigger than the current size of the image. Defaults to False.
antialias Whether to use an anti-aliasing filter when downsampling an image.
name A name for this operation (optional).
Raises
ValueError if the shape of images is incompatible with the shape arguments to this function
ValueError if size has an invalid shape or type.
ValueError if an unsupported resize method is specified.
Returns If images was 4-D, a 4-D float Tensor of shape [batch, new_height, new_width, channels]. If images was 3-D, a 3-D float Tensor of shape [new_height, new_width, channels]. | tensorflow.image.resize |
tf.image.ResizeMethod View source on GitHub See tf.image.resize for details.
Class Variables
AREA 'area'
BICUBIC 'bicubic'
BILINEAR 'bilinear'
GAUSSIAN 'gaussian'
LANCZOS3 'lanczos3'
LANCZOS5 'lanczos5'
MITCHELLCUBIC 'mitchellcubic'
NEAREST_NEIGHBOR 'nearest' | tensorflow.image.resizemethod |
tf.image.resize_with_crop_or_pad View source on GitHub Crops and/or pads an image to a target width and height. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.resize_image_with_crop_or_pad, tf.compat.v1.image.resize_with_crop_or_pad
tf.image.resize_with_crop_or_pad(
image, target_height, target_width
)
Resizes an image to a target width and height by either centrally cropping the image or padding it evenly with zeros. If width or height is greater than the specified target_width or target_height respectively, this op centrally crops along that dimension. If width or height is smaller than the specified target_width or target_height respectively, this op centrally pads with 0 along that dimension.
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
target_height Target height.
target_width Target width.
Raises
ValueError if target_height or target_width are zero or negative.
Returns Cropped and/or padded image. If images was 4-D, a 4-D float Tensor of shape [batch, new_height, new_width, channels]. If images was 3-D, a 3-D float Tensor of shape [new_height, new_width, channels]. | tensorflow.image.resize_with_crop_or_pad |
tf.image.resize_with_pad Resizes and pads an image to a target width and height.
tf.image.resize_with_pad(
image, target_height, target_width, method=ResizeMethod.BILINEAR,
antialias=False
)
Resizes an image to a target width and height by keeping the aspect ratio the same without distortion. If the target dimensions don't match the image dimensions, the image is resized and then padded with zeroes to match requested dimensions.
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
target_height Target height.
target_width Target width.
method Method to use for resizing image. See image.resize()
antialias Whether to use anti-aliasing when resizing. See 'image.resize()'.
Raises
ValueError if target_height or target_width are zero or negative.
Returns Resized and padded image. If images was 4-D, a 4-D float Tensor of shape [batch, new_height, new_width, channels]. If images was 3-D, a 3-D float Tensor of shape [new_height, new_width, channels]. | tensorflow.image.resize_with_pad |
tf.image.rgb_to_grayscale View source on GitHub Converts one or more images from RGB to Grayscale. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.rgb_to_grayscale
tf.image.rgb_to_grayscale(
images, name=None
)
Outputs a tensor of the same DType and rank as images. The size of the last dimension of the output is 1, containing the Grayscale value of the pixels.
original = tf.constant([[[1.0, 2.0, 3.0]]])
converted = tf.image.rgb_to_grayscale(original)
print(converted.numpy())
[[[1.81...]]]
Args
images The RGB tensor to convert. The last dimension must have size 3 and should contain RGB values.
name A name for the operation (optional).
Returns The converted grayscale image(s). | tensorflow.image.rgb_to_grayscale |
tf.image.rgb_to_hsv Converts one or more images from RGB to HSV. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.rgb_to_hsv
tf.image.rgb_to_hsv(
images, name=None
)
Outputs a tensor of the same shape as the images tensor, containing the HSV value of the pixels. The output is only well defined if the value in images are in [0,1]. output[..., 0] contains hue, output[..., 1] contains saturation, and output[..., 2] contains value. All HSV values are in [0,1]. A hue of 0 corresponds to pure red, hue 1/3 is pure green, and 2/3 is pure blue. Usage Example:
blue_image = tf.stack([
tf.zeros([5,5]),
tf.zeros([5,5]),
tf.ones([5,5])],
axis=-1)
blue_hsv_image = tf.image.rgb_to_hsv(blue_image)
blue_hsv_image[0,0].numpy()
array([0.6666667, 1. , 1. ], dtype=float32)
Args
images A Tensor. Must be one of the following types: half, bfloat16, float32, float64. 1-D or higher rank. RGB data to convert. Last dimension must be size 3.
name A name for the operation (optional).
Returns A Tensor. Has the same type as images. | tensorflow.image.rgb_to_hsv |
tf.image.rgb_to_yiq View source on GitHub Converts one or more images from RGB to YIQ. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.rgb_to_yiq
tf.image.rgb_to_yiq(
images
)
Outputs a tensor of the same shape as the images tensor, containing the YIQ value of the pixels. The output is only well defined if the value in images are in [0,1]. Usage Example:
x = tf.constant([[[1.0, 2.0, 3.0]]])
tf.image.rgb_to_yiq(x)
<tf.Tensor: shape=(1, 1, 3), dtype=float32,
numpy=array([[[ 1.815 , -0.91724455, 0.09962624]]], dtype=float32)>
Args
images 2-D or higher rank. Image data to convert. Last dimension must be size 3.
Returns
images tensor with the same shape as images. | tensorflow.image.rgb_to_yiq |
tf.image.rgb_to_yuv View source on GitHub Converts one or more images from RGB to YUV. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.rgb_to_yuv
tf.image.rgb_to_yuv(
images
)
Outputs a tensor of the same shape as the images tensor, containing the YUV value of the pixels. The output is only well defined if the value in images are in [0, 1]. There are two ways of representing an image: [0, 255] pixel values range or 0, 1 pixel values range. Users need to convert the input image into a float [0, 1] range.
Args
images 2-D or higher rank. Image data to convert. Last dimension must be size 3.
Returns
images tensor with the same shape as images. | tensorflow.image.rgb_to_yuv |
tf.image.rot90 View source on GitHub Rotate image(s) counter-clockwise by 90 degrees. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.rot90
tf.image.rot90(
image, k=1, name=None
)
For example:
a=tf.constant([[[1],[2]],
[[3],[4]]])
# rotating `a` counter clockwise by 90 degrees
a_rot=tf.image.rot90(a)
print(a_rot[...,0].numpy())
[[2 4]
[1 3]]
# rotating `a` counter clockwise by 270 degrees
a_rot=tf.image.rot90(a, k=3)
print(a_rot[...,0].numpy())
[[3 1]
[4 2]]
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
k A scalar integer. The number of times the image is rotated by 90 degrees.
name A name for this operation (optional).
Returns A rotated tensor of the same type and shape as image.
Raises
ValueError if the shape of image not supported. | tensorflow.image.rot90 |
tf.image.sample_distorted_bounding_box View source on GitHub Generate a single randomly distorted bounding box for an image.
tf.image.sample_distorted_bounding_box(
image_size, bounding_boxes, seed=0, min_object_covered=0.1,
aspect_ratio_range=None, area_range=None, max_attempts=None,
use_image_if_no_bounding_boxes=None, name=None
)
Bounding box annotations are often supplied in addition to ground-truth labels in image recognition or object localization tasks. A common technique for training such a system is to randomly distort an image while preserving its content, i.e. data augmentation. This Op outputs a randomly distorted localization of an object, i.e. bounding box, given an image_size, bounding_boxes and a series of constraints. The output of this Op is a single bounding box that may be used to crop the original image. The output is returned as 3 tensors: begin, size and bboxes. The first 2 tensors can be fed directly into tf.slice to crop the image. The latter may be supplied to tf.image.draw_bounding_boxes to visualize what the bounding box looks like. Bounding boxes are supplied and returned as [y_min, x_min, y_max, x_max]. The bounding box coordinates are floats in [0.0, 1.0] relative to the width and the height of the underlying image. For example, # Generate a single distorted bounding box.
begin, size, bbox_for_draw = tf.image.sample_distorted_bounding_box(
tf.shape(image),
bounding_boxes=bounding_boxes,
min_object_covered=0.1)
# Draw the bounding box in an image summary.
image_with_box = tf.image.draw_bounding_boxes(tf.expand_dims(image, 0),
bbox_for_draw)
tf.compat.v1.summary.image('images_with_box', image_with_box)
# Employ the bounding box to distort the image.
distorted_image = tf.slice(image, begin, size)
Note that if no bounding box information is available, setting use_image_if_no_bounding_boxes = true will assume there is a single implicit bounding box covering the whole image. If use_image_if_no_bounding_boxes is false and no bounding boxes are supplied, an error is raised.
Args
image_size A Tensor. Must be one of the following types: uint8, int8, int16, int32, int64. 1-D, containing [height, width, channels].
bounding_boxes A Tensor of type float32. 3-D with shape [batch, N, 4] describing the N bounding boxes associated with the image.
seed An optional int. Defaults to 0. If seed is set to non-zero, the random number generator is seeded by the given seed. Otherwise, it is seeded by a random seed.
min_object_covered A Tensor of type float32. Defaults to 0.1. The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied.
aspect_ratio_range An optional list of floats. Defaults to [0.75, 1.33]. The cropped area of the image must have an aspect ratio = width / height within this range.
area_range An optional list of floats. Defaults to [0.05, 1]. The cropped area of the image must contain a fraction of the supplied image within this range.
max_attempts An optional int. Defaults to 100. Number of attempts at generating a cropped region of the image of the specified constraints. After max_attempts failures, return the entire image.
use_image_if_no_bounding_boxes An optional bool. Defaults to False. Controls behavior if no bounding boxes supplied. If true, assume an implicit bounding box covering the whole input. If false, raise an error.
name A name for the operation (optional).
Returns A tuple of Tensor objects (begin, size, bboxes). begin A Tensor. Has the same type as image_size. 1-D, containing [offset_height, offset_width, 0]. Provide as input to tf.slice.
size A Tensor. Has the same type as image_size. 1-D, containing [target_height, target_width, -1]. Provide as input to tf.slice.
bboxes A Tensor of type float32. 3-D with shape [1, 1, 4] containing the distorted bounding box. Provide as input to tf.image.draw_bounding_boxes. | tensorflow.image.sample_distorted_bounding_box |
tf.image.sobel_edges View source on GitHub Returns a tensor holding Sobel edge maps. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.sobel_edges
tf.image.sobel_edges(
image
)
Arguments
image Image tensor with shape [batch_size, h, w, d] and type float32 or float64. The image(s) must be 2x2 or larger.
Returns Tensor holding edge maps for each channel. Returns a tensor with shape [batch_size, h, w, d, 2] where the last two dimensions hold [[dy[0], dx[0]], [dy[1], dx[1]], ..., [dy[d-1], dx[d-1]]] calculated using the Sobel filter. | tensorflow.image.sobel_edges |
tf.image.ssim View source on GitHub Computes SSIM index between img1 and img2. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.ssim
tf.image.ssim(
img1, img2, max_val, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03
)
This function is based on the standard SSIM implementation from: Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image quality assessment: from error visibility to structural similarity. IEEE transactions on image processing.
Note: The true SSIM is only defined on grayscale. This function does not perform any colorspace transform. (If the input is already YUV, then it will compute YUV SSIM average.)
Details: 11x11 Gaussian filter of width 1.5 is used. k1 = 0.01, k2 = 0.03 as in the original paper. The image sizes must be at least 11x11 because of the filter size. Example: # Read images from file.
im1 = tf.decode_png('path/to/im1.png')
im2 = tf.decode_png('path/to/im2.png')
# Compute SSIM over tf.uint8 Tensors.
ssim1 = tf.image.ssim(im1, im2, max_val=255, filter_size=11,
filter_sigma=1.5, k1=0.01, k2=0.03)
# Compute SSIM over tf.float32 Tensors.
im1 = tf.image.convert_image_dtype(im1, tf.float32)
im2 = tf.image.convert_image_dtype(im2, tf.float32)
ssim2 = tf.image.ssim(im1, im2, max_val=1.0, filter_size=11,
filter_sigma=1.5, k1=0.01, k2=0.03)
# ssim1 and ssim2 both have type tf.float32 and are almost equal.
Args
img1 First image batch.
img2 Second image batch.
max_val The dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values).
filter_size Default value 11 (size of gaussian filter).
filter_sigma Default value 1.5 (width of gaussian filter).
k1 Default value 0.01
k2 Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so it would be better if we took the values in the range of 0 < K2 < 0.4).
Returns A tensor containing an SSIM value for each image in batch. Returned SSIM values are in range (-1, 1], when pixel values are non-negative. Returns a tensor with shape: broadcast(img1.shape[:-3], img2.shape[:-3]). | tensorflow.image.ssim |
tf.image.ssim_multiscale View source on GitHub Computes the MS-SSIM between img1 and img2. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.ssim_multiscale
tf.image.ssim_multiscale(
img1, img2, max_val, power_factors=_MSSSIM_WEIGHTS, filter_size=11,
filter_sigma=1.5, k1=0.01, k2=0.03
)
This function assumes that img1 and img2 are image batches, i.e. the last three dimensions are [height, width, channels].
Note: The true SSIM is only defined on grayscale. This function does not perform any colorspace transform. (If the input is already YUV, then it will compute YUV SSIM average.)
Original paper: Wang, Zhou, Eero P. Simoncelli, and Alan C. Bovik. "Multiscale structural similarity for image quality assessment." Signals, Systems and Computers, 2004.
Arguments
img1 First image batch.
img2 Second image batch. Must have the same rank as img1.
max_val The dynamic range of the images (i.e., the difference between the maximum the and minimum allowed values).
power_factors Iterable of weights for each of the scales. The number of scales used is the length of the list. Index 0 is the unscaled resolution's weight and each increasing scale corresponds to the image being downsampled by 2. Defaults to (0.0448, 0.2856, 0.3001, 0.2363, 0.1333), which are the values obtained in the original paper.
filter_size Default value 11 (size of gaussian filter).
filter_sigma Default value 1.5 (width of gaussian filter).
k1 Default value 0.01
k2 Default value 0.03 (SSIM is less sensitivity to K2 for lower values, so it would be better if we took the values in the range of 0 < K2 < 0.4).
Returns A tensor containing an MS-SSIM value for each image in batch. The values are in range [0, 1]. Returns a tensor with shape: broadcast(img1.shape[:-3], img2.shape[:-3]). | tensorflow.image.ssim_multiscale |
tf.image.stateless_random_brightness Adjust the brightness of images by a random factor deterministically.
tf.image.stateless_random_brightness(
image, max_delta, seed
)
Equivalent to adjust_brightness() using a delta randomly picked in the interval [-max_delta, max_delta). Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
seed = (1, 2)
tf.image.stateless_random_brightness(x, 0.2, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 1.1376241, 2.1376243, 3.1376243],
[ 4.1376243, 5.1376243, 6.1376243]],
[[ 7.1376243, 8.137624 , 9.137624 ],
[10.137624 , 11.137624 , 12.137624 ]]], dtype=float32)>
Args
image An image or images to adjust.
max_delta float, must be non-negative.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns The brightness-adjusted image(s).
Raises
ValueError if max_delta is negative. | tensorflow.image.stateless_random_brightness |
tf.image.stateless_random_contrast Adjust the contrast of images by a random factor deterministically.
tf.image.stateless_random_contrast(
image, lower, upper, seed
)
Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed).
Args
image An image tensor with 3 or more dimensions.
lower float. Lower bound for the random contrast factor.
upper float. Upper bound for the random contrast factor.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.) Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
seed = (1, 2)
tf.image.stateless_random_contrast(x, 0.2, 0.5, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[3.4605184, 4.4605184, 5.4605184],
[4.820173 , 5.820173 , 6.820173 ]],
[[6.179827 , 7.179827 , 8.179828 ],
[7.5394816, 8.539482 , 9.539482 ]]], dtype=float32)>
Returns The contrast-adjusted image(s).
Raises
ValueError if upper <= lower or if lower < 0. | tensorflow.image.stateless_random_contrast |
tf.image.stateless_random_crop Randomly crops a tensor to a given size in a deterministic manner.
tf.image.stateless_random_crop(
value, size, seed, name=None
)
Slices a shape size portion out of value at a uniformly chosen offset. Requires value.shape >= size. If a dimension should not be cropped, pass the full size of that dimension. For example, RGB images can be cropped with size = [crop_height, crop_width, 3]. Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Usage Example:
image = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
seed = (1, 2)
tf.image.stateless_random_crop(value=image, size=(1, 2, 3), seed=seed)
<tf.Tensor: shape=(1, 2, 3), dtype=int32, numpy=
array([[[1, 2, 3],
[4, 5, 6]]], dtype=int32)>
Args
value Input tensor to crop.
size 1-D tensor with size the rank of value.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
name A name for this operation (optional).
Returns A cropped tensor of the same rank as value and shape size. | tensorflow.image.stateless_random_crop |
tf.image.stateless_random_flip_left_right Randomly flip an image horizontally (left to right) deterministically.
tf.image.stateless_random_flip_left_right(
image, seed
)
Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Example usage:
image = np.array([[[1], [2]], [[3], [4]]])
seed = (2, 3)
tf.image.stateless_random_flip_left_right(image, seed).numpy().tolist()
[[[2], [1]], [[4], [3]]]
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns A tensor of the same type and shape as image. | tensorflow.image.stateless_random_flip_left_right |
tf.image.stateless_random_flip_up_down Randomly flip an image vertically (upside down) deterministically.
tf.image.stateless_random_flip_up_down(
image, seed
)
Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Example usage:
image = np.array([[[1], [2]], [[3], [4]]])
seed = (2, 3)
tf.image.stateless_random_flip_up_down(image, seed).numpy().tolist()
[[[3], [4]], [[1], [2]]]
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns A tensor of the same type and shape as image. | tensorflow.image.stateless_random_flip_up_down |
tf.image.stateless_random_hue Adjust the hue of RGB images by a random factor deterministically.
tf.image.stateless_random_hue(
image, max_delta, seed
)
Equivalent to adjust_hue() but uses a delta randomly picked in the interval [-max_delta, max_delta). Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). max_delta must be in the interval [0, 0.5]. Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
seed = (1, 2)
tf.image.stateless_random_hue(x, 0.2, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 1.6514902, 1. , 3. ],
[ 4.65149 , 4. , 6. ]],
[[ 7.65149 , 7. , 9. ],
[10.65149 , 10. , 12. ]]], dtype=float32)>
Args
image RGB image or images. The size of the last dimension must be 3.
max_delta float. The maximum value for the random delta.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if max_delta is invalid. | tensorflow.image.stateless_random_hue |
tf.image.stateless_random_jpeg_quality Deterministically radomize jpeg encoding quality for inducing jpeg noise.
tf.image.stateless_random_jpeg_quality(
image, min_jpeg_quality, max_jpeg_quality, seed
)
Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). min_jpeg_quality must be in the interval [0, 100] and less than max_jpeg_quality. max_jpeg_quality must be in the interval [0, 100]. Usage Example:
x = [[[1, 2, 3],
[4, 5, 6]],
[[7, 8, 9],
[10, 11, 12]]]
x_uint8 = tf.cast(x, tf.uint8)
seed = (1, 2)
tf.image.stateless_random_jpeg_quality(x_uint8, 75, 95, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=uint8, numpy=
array([[[ 0, 4, 5],
[ 1, 5, 6]],
[[ 5, 9, 10],
[ 5, 9, 10]]], dtype=uint8)>
Args
image 3D image. Size of the last dimension must be 1 or 3.
min_jpeg_quality Minimum jpeg encoding quality to use.
max_jpeg_quality Maximum jpeg encoding quality to use.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if min_jpeg_quality or max_jpeg_quality is invalid. | tensorflow.image.stateless_random_jpeg_quality |
tf.image.stateless_random_saturation Adjust the saturation of RGB images by a random factor deterministically.
tf.image.stateless_random_saturation(
image, lower, upper, seed=None
)
Equivalent to adjust_saturation() but uses a saturation_factor randomly picked in the interval [lower, upper). Guarantees the same results given the same seed independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
seed = (1, 2)
tf.image.stateless_random_saturation(x, 0.5, 1.0, seed)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 1.1559395, 2.0779698, 3. ],
[ 4.1559396, 5.07797 , 6. ]],
[[ 7.1559396, 8.07797 , 9. ],
[10.155939 , 11.07797 , 12. ]]], dtype=float32)>
Args
image RGB image or images. The size of the last dimension must be 3.
lower float. Lower bound for the random saturation factor.
upper float. Upper bound for the random saturation factor.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
Returns Adjusted image(s), same shape and DType as image.
Raises
ValueError if upper <= lower or if lower < 0. | tensorflow.image.stateless_random_saturation |
tf.image.stateless_sample_distorted_bounding_box Generate a randomly distorted bounding box for an image deterministically.
tf.image.stateless_sample_distorted_bounding_box(
image_size, bounding_boxes, seed, min_object_covered=0.1,
aspect_ratio_range=None, area_range=None, max_attempts=None,
use_image_if_no_bounding_boxes=None, name=None
)
Bounding box annotations are often supplied in addition to ground-truth labels in image recognition or object localization tasks. A common technique for training such a system is to randomly distort an image while preserving its content, i.e. data augmentation. This Op, given the same seed, deterministically outputs a randomly distorted localization of an object, i.e. bounding box, given an image_size, bounding_boxes and a series of constraints. The output of this Op is a single bounding box that may be used to crop the original image. The output is returned as 3 tensors: begin, size and bboxes. The first 2 tensors can be fed directly into tf.slice to crop the image. The latter may be supplied to tf.image.draw_bounding_boxes to visualize what the bounding box looks like. Bounding boxes are supplied and returned as [y_min, x_min, y_max, x_max]. The bounding box coordinates are floats in [0.0, 1.0] relative to the width and the height of the underlying image. The output of this Op is guaranteed to be the same given the same seed and is independent of how many times the function is called, and independent of global seed settings (e.g. tf.random.set_seed). Example usage:
image = np.array([[[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]]])
bbox = tf.constant(
[0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
seed = (1, 2)
# Generate a single distorted bounding box.
bbox_begin, bbox_size, bbox_draw = (
tf.image.stateless_sample_distorted_bounding_box(
tf.shape(image), bounding_boxes=bbox, seed=seed))
# Employ the bounding box to distort the image.
tf.slice(image, bbox_begin, bbox_size)
<tf.Tensor: shape=(2, 2, 1), dtype=int64, numpy=
array([[[1],
[2]],
[[4],
[5]]])>
# Draw the bounding box in an image summary.
colors = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
tf.image.draw_bounding_boxes(
tf.expand_dims(tf.cast(image, tf.float32),0), bbox_draw, colors)
<tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy=
array([[[[1.],
[1.],
[3.]],
[[1.],
[1.],
[6.]],
[[7.],
[8.],
[9.]]]], dtype=float32)>
Note that if no bounding box information is available, setting use_image_if_no_bounding_boxes = true will assume there is a single implicit bounding box covering the whole image. If use_image_if_no_bounding_boxes is false and no bounding boxes are supplied, an error is raised.
Args
image_size A Tensor. Must be one of the following types: uint8, int8, int16, int32, int64. 1-D, containing [height, width, channels].
bounding_boxes A Tensor of type float32. 3-D with shape [batch, N, 4] describing the N bounding boxes associated with the image.
seed A shape [2] Tensor, the seed to the random number generator. Must have dtype int32 or int64. (When using XLA, only int32 is allowed.)
min_object_covered A Tensor of type float32. Defaults to 0.1. The cropped area of the image must contain at least this fraction of any bounding box supplied. The value of this parameter should be non-negative. In the case of 0, the cropped area does not need to overlap any of the bounding boxes supplied.
aspect_ratio_range An optional list of floats. Defaults to [0.75, 1.33]. The cropped area of the image must have an aspect ratio = width / height within this range.
area_range An optional list of floats. Defaults to [0.05, 1]. The cropped area of the image must contain a fraction of the supplied image within this range.
max_attempts An optional int. Defaults to 100. Number of attempts at generating a cropped region of the image of the specified constraints. After max_attempts failures, return the entire image.
use_image_if_no_bounding_boxes An optional bool. Defaults to False. Controls behavior if no bounding boxes supplied. If true, assume an implicit bounding box covering the whole input. If false, raise an error.
name A name for the operation (optional).
Returns A tuple of Tensor objects (begin, size, bboxes). begin A Tensor. Has the same type as image_size. 1-D, containing [offset_height, offset_width, 0]. Provide as input to tf.slice.
size A Tensor. Has the same type as image_size. 1-D, containing [target_height, target_width, -1]. Provide as input to tf.slice.
bboxes A Tensor of type float32. 3-D with shape [1, 1, 4] containing the distorted bounding box. Provide as input to tf.image.draw_bounding_boxes. | tensorflow.image.stateless_sample_distorted_bounding_box |
tf.image.total_variation View source on GitHub Calculate and return the total variation for one or more images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.total_variation
tf.image.total_variation(
images, name=None
)
The total variation is the sum of the absolute differences for neighboring pixel-values in the input images. This measures how much noise is in the images. This can be used as a loss-function during optimization so as to suppress noise in images. If you have a batch of images, then you should calculate the scalar loss-value as the sum: loss = tf.reduce_sum(tf.image.total_variation(images)) This implements the anisotropic 2-D version of the formula described here: https://en.wikipedia.org/wiki/Total_variation_denoising
Args
images 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
name A name for the operation (optional).
Raises
ValueError if images.shape is not a 3-D or 4-D vector.
Returns The total variation of images. If images was 4-D, return a 1-D float Tensor of shape [batch] with the total variation for each image in the batch. If images was 3-D, return a scalar float with the total variation for that image. | tensorflow.image.total_variation |
tf.image.transpose View source on GitHub Transpose image(s) by swapping the height and width dimension. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.transpose, tf.compat.v1.image.transpose_image
tf.image.transpose(
image, name=None
)
Usage Example:
x = [[[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0]],
[[7.0, 8.0, 9.0],
[10.0, 11.0, 12.0]]]
tf.image.transpose(x)
<tf.Tensor: shape=(2, 2, 3), dtype=float32, numpy=
array([[[ 1., 2., 3.],
[ 7., 8., 9.]],
[[ 4., 5., 6.],
[10., 11., 12.]]], dtype=float32)>
Args
image 4-D Tensor of shape [batch, height, width, channels] or 3-D Tensor of shape [height, width, channels].
name A name for this operation (optional).
Returns If image was 4-D, a 4-D float Tensor of shape [batch, width, height, channels] If image was 3-D, a 3-D float Tensor of shape [width, height, channels]
Raises
ValueError if the shape of image not supported. Usage Example:
image = [[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
[[9, 10], [11, 12]]]
image = tf.constant(image)
tf.image.transpose(image)
<tf.Tensor: shape=(2, 3, 2), dtype=int32, numpy=
array([[[ 1, 2],
[ 5, 6],
[ 9, 10]],
[[ 3, 4],
[ 7, 8],
[11, 12]]], dtype=int32)> | tensorflow.image.transpose |
tf.image.yiq_to_rgb View source on GitHub Converts one or more images from YIQ to RGB. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.yiq_to_rgb
tf.image.yiq_to_rgb(
images
)
Outputs a tensor of the same shape as the images tensor, containing the RGB value of the pixels. The output is only well defined if the Y value in images are in [0,1], I value are in [-0.5957,0.5957] and Q value are in [-0.5226,0.5226].
Args
images 2-D or higher rank. Image data to convert. Last dimension must be size 3.
Returns
images tensor with the same shape as images. | tensorflow.image.yiq_to_rgb |
tf.image.yuv_to_rgb View source on GitHub Converts one or more images from YUV to RGB. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.image.yuv_to_rgb
tf.image.yuv_to_rgb(
images
)
Outputs a tensor of the same shape as the images tensor, containing the RGB value of the pixels. The output is only well defined if the Y value in images are in [0,1], U and V value are in [-0.5,0.5]. As per the above description, you need to scale your YUV images if their pixel values are not in the required range. Below given example illustrates preprocessing of each channel of images before feeding them to yuv_to_rgb. yuv_images = tf.random.uniform(shape=[100, 64, 64, 3], maxval=255)
last_dimension_axis = len(yuv_images.shape) - 1
yuv_tensor_images = tf.truediv(
tf.subtract(
yuv_images,
tf.reduce_min(yuv_images)
),
tf.subtract(
tf.reduce_max(yuv_images),
tf.reduce_min(yuv_images)
)
)
y, u, v = tf.split(yuv_tensor_images, 3, axis=last_dimension_axis)
target_uv_min, target_uv_max = -0.5, 0.5
u = u * (target_uv_max - target_uv_min) + target_uv_min
v = v * (target_uv_max - target_uv_min) + target_uv_min
preprocessed_yuv_images = tf.concat([y, u, v], axis=last_dimension_axis)
rgb_tensor_images = tf.image.yuv_to_rgb(preprocessed_yuv_images)
Args
images 2-D or higher rank. Image data to convert. Last dimension must be size 3.
Returns
images tensor with the same shape as images. | tensorflow.image.yuv_to_rgb |
tf.IndexedSlices View source on GitHub A sparse representation of a set of tensor slices at given indices. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.IndexedSlices
tf.IndexedSlices(
values, indices, dense_shape=None
)
This class is a simple wrapper for a pair of Tensor objects:
values: A Tensor of any dtype with shape [D0, D1, ..., Dn].
indices: A 1-D integer Tensor with shape [D0]. An IndexedSlices is typically used to represent a subset of a larger tensor dense of shape [LARGE0, D1, .. , DN] where LARGE0 >> D0. The values in indices are the indices in the first dimension of the slices that have been extracted from the larger tensor. The dense tensor dense represented by an IndexedSlices slices has dense[slices.indices[i], :, :, :, ...] = slices.values[i, :, :, :, ...]
The IndexedSlices class is used principally in the definition of gradients for operations that have sparse gradients (e.g. tf.gather). Contrast this representation with tf.sparse.SparseTensor, which uses multi-dimensional indices and scalar values.
Attributes
dense_shape A 1-D Tensor containing the shape of the corresponding dense tensor.
device The name of the device on which values will be produced, or None.
dtype The DType of elements in this tensor.
graph The Graph that contains the values, indices, and shape tensors.
indices A 1-D Tensor containing the indices of the slices.
name The name of this IndexedSlices.
op The Operation that produces values as an output.
shape Gets the tf.TensorShape representing the shape of the dense tensor.
values A Tensor containing the values of the slices. Methods consumers View source
consumers()
__neg__ View source
__neg__() | tensorflow.indexedslices |
tf.IndexedSlicesSpec View source on GitHub Type specification for a tf.IndexedSlices. Inherits From: TypeSpec View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.IndexedSlicesSpec
tf.IndexedSlicesSpec(
shape=None, dtype=tf.dtypes.float32, indices_dtype=tf.dtypes.int64,
dense_shape_dtype=None, indices_shape=None
)
Args
shape The dense shape of the IndexedSlices, or None to allow any dense shape.
dtype tf.DType of values in the IndexedSlices.
indices_dtype tf.DType of the indices in the IndexedSlices. One of tf.int32 or tf.int64.
dense_shape_dtype tf.DType of the dense_shape in the IndexedSlices. One of tf.int32, tf.int64, or None (if the IndexedSlices has no dense_shape tensor).
indices_shape The shape of the indices component, which indicates how many slices are in the IndexedSlices.
Attributes
value_type
Methods is_compatible_with View source
is_compatible_with(
spec_or_value
)
Returns true if spec_or_value is compatible with this TypeSpec. most_specific_compatible_type View source
most_specific_compatible_type(
other
)
Returns the most specific TypeSpec compatible with self and other.
Args
other A TypeSpec.
Raises
ValueError If there is no TypeSpec that is compatible with both self and other. __eq__ View source
__eq__(
other
)
Return self==value. __ne__ View source
__ne__(
other
)
Return self!=value. | tensorflow.indexedslicesspec |
tf.init_scope View source on GitHub A context manager that lifts ops out of control-flow scopes and function-building graphs. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.init_scope
@tf_contextlib.contextmanager
tf.init_scope()
There is often a need to lift variable initialization ops out of control-flow scopes, function-building graphs, and gradient tapes. Entering an init_scope is a mechanism for satisfying these desiderata. In particular, entering an init_scope has three effects: (1) All control dependencies are cleared the moment the scope is entered; this is equivalent to entering the context manager returned from control_dependencies(None), which has the side-effect of exiting control-flow scopes like tf.cond and tf.while_loop. (2) All operations that are created while the scope is active are lifted into the lowest context on the context_stack that is not building a graph function. Here, a context is defined as either a graph or an eager context. Every context switch, i.e., every installation of a graph as the default graph and every switch into eager mode, is logged in a thread-local stack called context_switches; the log entry for a context switch is popped from the stack when the context is exited. Entering an init_scope is equivalent to crawling up context_switches, finding the first context that is not building a graph function, and entering it. A caveat is that if graph mode is enabled but the default graph stack is empty, then entering an init_scope will simply install a fresh graph as the default one. (3) The gradient tape is paused while the scope is active. When eager execution is enabled, code inside an init_scope block runs with eager execution enabled even when tracing a tf.function. For example: tf.compat.v1.enable_eager_execution()
@tf.function
def func():
# A function constructs TensorFlow graphs,
# it does not execute eagerly.
assert not tf.executing_eagerly()
with tf.init_scope():
# Initialization runs with eager execution enabled
assert tf.executing_eagerly()
Raises
RuntimeError if graph state is incompatible with this initialization. | tensorflow.init_scope |
tf.inside_function Indicates whether the caller code is executing inside a tf.function.
tf.inside_function()
Returns Boolean, True if the caller code is executing inside a tf.function rather than eagerly.
Example:
tf.inside_function()
False
@tf.function
def f():
print(tf.inside_function())
f()
True | tensorflow.inside_function |
Module: tf.io Public API for tf.io namespace. Modules gfile module: Public API for tf.io.gfile namespace. Classes class FixedLenFeature: Configuration for parsing a fixed-length input feature. class FixedLenSequenceFeature: Configuration for parsing a variable-length input feature into a Tensor. class RaggedFeature: Configuration for passing a RaggedTensor input feature. class SparseFeature: Configuration for parsing a sparse input feature from an Example. class TFRecordOptions: Options used for manipulating TFRecord files. class TFRecordWriter: A class to write records to a TFRecords file. class VarLenFeature: Configuration for parsing a variable-length input feature. Functions decode_and_crop_jpeg(...): Decode and Crop a JPEG-encoded image to a uint8 tensor. decode_base64(...): Decode web-safe base64-encoded strings. decode_bmp(...): Decode the first frame of a BMP-encoded image to a uint8 tensor. decode_compressed(...): Decompress strings. decode_csv(...): Convert CSV records to tensors. Each column maps to one tensor. decode_gif(...): Decode the frame(s) of a GIF-encoded image to a uint8 tensor. decode_image(...): Function for decode_bmp, decode_gif, decode_jpeg, and decode_png. decode_jpeg(...): Decode a JPEG-encoded image to a uint8 tensor. decode_json_example(...): Convert JSON-encoded Example records to binary protocol buffer strings. decode_png(...): Decode a PNG-encoded image to a uint8 or uint16 tensor. decode_proto(...): The op extracts fields from a serialized protocol buffers message into tensors. decode_raw(...): Convert raw byte strings into tensors. deserialize_many_sparse(...): Deserialize and concatenate SparseTensors from a serialized minibatch. encode_base64(...): Encode strings into web-safe base64 format. encode_jpeg(...): JPEG-encode an image. encode_png(...): PNG-encode an image. encode_proto(...): The op serializes protobuf messages provided in the input tensors. extract_jpeg_shape(...): Extract the shape information of a JPEG-encoded image. is_jpeg(...): Convenience function to check if the 'contents' encodes a JPEG image. match_filenames_once(...): Save the list of files matching pattern, so it is only computed once. matching_files(...): Returns the set of files matching one or more glob patterns. parse_example(...): Parses Example protos into a dict of tensors. parse_sequence_example(...): Parses a batch of SequenceExample protos. parse_single_example(...): Parses a single Example proto. parse_single_sequence_example(...): Parses a single SequenceExample proto. parse_tensor(...): Transforms a serialized tensorflow.TensorProto proto into a Tensor. read_file(...): Reads and outputs the entire contents of the input filename. serialize_many_sparse(...): Serialize N-minibatch SparseTensor into an [N, 3] Tensor. serialize_sparse(...): Serialize a SparseTensor into a 3-vector (1-D Tensor) object. serialize_tensor(...): Transforms a Tensor into a serialized TensorProto proto. write_file(...): Writes contents to the file at input filename. Creates file and recursively write_graph(...): Writes a graph proto to a file. | tensorflow.io |
tf.io.decode_and_crop_jpeg Decode and Crop a JPEG-encoded image to a uint8 tensor. View aliases Main aliases
tf.image.decode_and_crop_jpeg Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_and_crop_jpeg, tf.compat.v1.io.decode_and_crop_jpeg
tf.io.decode_and_crop_jpeg(
contents, crop_window, channels=0, ratio=1, fancy_upscaling=True,
try_recover_truncated=False, acceptable_fraction=1, dct_method='',
name=None
)
The attr channels indicates the desired number of color channels for the decoded image. Accepted values are: 0: Use the number of channels in the JPEG-encoded image. 1: output a grayscale image. 3: output an RGB image. If needed, the JPEG-encoded image is transformed to match the requested number of color channels. The attr ratio allows downscaling the image by an integer factor during decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than downscaling the image later. It is equivalent to a combination of decode and crop, but much faster by only decoding partial jpeg image.
Args
contents A Tensor of type string. 0-D. The JPEG-encoded image.
crop_window A Tensor of type int32. 1-D. The crop window: [crop_y, crop_x, crop_height, crop_width].
channels An optional int. Defaults to 0. Number of color channels for the decoded image.
ratio An optional int. Defaults to 1. Downscaling ratio.
fancy_upscaling An optional bool. Defaults to True. If true use a slower but nicer upscaling of the chroma planes (yuv420/422 only).
try_recover_truncated An optional bool. Defaults to False. If true try to recover an image from truncated input.
acceptable_fraction An optional float. Defaults to 1. The minimum required fraction of lines before a truncated input is accepted.
dct_method An optional string. Defaults to "". string specifying a hint about the algorithm used for decompression. Defaults to "" which maps to a system-specific default. Currently valid values are ["INTEGER_FAST", "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal jpeg library changes to a version that does not have that specific option.)
name A name for the operation (optional).
Returns A Tensor of type uint8. | tensorflow.io.decode_and_crop_jpeg |
tf.io.decode_base64 Decode web-safe base64-encoded strings. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.decode_base64, tf.compat.v1.io.decode_base64
tf.io.decode_base64(
input, name=None
)
Input may or may not have padding at the end. See EncodeBase64 for padding. Web-safe means that input must use - and _ instead of + and /.
Args
input A Tensor of type string. Base64 strings to decode.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.decode_base64 |
tf.io.decode_bmp Decode the first frame of a BMP-encoded image to a uint8 tensor. View aliases Main aliases
tf.image.decode_bmp Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_bmp, tf.compat.v1.io.decode_bmp
tf.io.decode_bmp(
contents, channels=0, name=None
)
The attr channels indicates the desired number of color channels for the decoded image. Accepted values are: 0: Use the number of channels in the BMP-encoded image. 3: output an RGB image. 4: output an RGBA image.
Args
contents A Tensor of type string. 0-D. The BMP-encoded image.
channels An optional int. Defaults to 0.
name A name for the operation (optional).
Returns A Tensor of type uint8. | tensorflow.io.decode_bmp |
tf.io.decode_compressed Decompress strings. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.decode_compressed, tf.compat.v1.io.decode_compressed
tf.io.decode_compressed(
bytes, compression_type='', name=None
)
This op decompresses each element of the bytes input Tensor, which is assumed to be compressed using the given compression_type. The output is a string Tensor of the same shape as bytes, each element containing the decompressed data from the corresponding element in bytes.
Args
bytes A Tensor of type string. A Tensor of string which is compressed.
compression_type An optional string. Defaults to "". A scalar containing either (i) the empty string (no compression), (ii) "ZLIB", or (iii) "GZIP".
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.decode_compressed |
tf.io.decode_csv View source on GitHub Convert CSV records to tensors. Each column maps to one tensor.
tf.io.decode_csv(
records, record_defaults, field_delim=',', use_quote_delim=True,
na_value='', select_cols=None, name=None
)
RFC 4180 format is expected for the CSV records. (https://tools.ietf.org/html/rfc4180) Note that we allow leading and trailing spaces with int or float field.
Args
records A Tensor of type string. Each string is a record/row in the csv and all records should have the same format.
record_defaults A list of Tensor objects with specific types. Acceptable types are float32, float64, int32, int64, string. One tensor per column of the input record, with either a scalar default value for that column or an empty vector if the column is required.
field_delim An optional string. Defaults to ",". char delimiter to separate fields in a record.
use_quote_delim An optional bool. Defaults to True. If false, treats double quotation marks as regular characters inside of the string fields (ignoring RFC 4180, Section 2, Bullet 5).
na_value Additional string to recognize as NA/NaN.
select_cols Optional sorted list of column indices to select. If specified, only this subset of columns will be parsed and returned.
name A name for the operation (optional).
Returns A list of Tensor objects. Has the same type as record_defaults. Each tensor will have the same shape as records.
Raises
ValueError If any of the arguments is malformed. | tensorflow.io.decode_csv |
tf.io.decode_gif Decode the frame(s) of a GIF-encoded image to a uint8 tensor. View aliases Main aliases
tf.image.decode_gif Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_gif, tf.compat.v1.io.decode_gif
tf.io.decode_gif(
contents, name=None
)
GIF images with frame or transparency compression are not supported. On Linux and MacOS systems, convert animated GIFs from compressed to uncompressed by running: convert $src.gif -coalesce $dst.gif
This op also supports decoding JPEGs and PNGs, though it is cleaner to use tf.io.decode_image.
Args
contents A Tensor of type string. 0-D. The GIF-encoded image.
name A name for the operation (optional).
Returns A Tensor of type uint8. | tensorflow.io.decode_gif |
tf.io.decode_image View source on GitHub Function for decode_bmp, decode_gif, decode_jpeg, and decode_png. View aliases Main aliases
tf.image.decode_image Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_image, tf.compat.v1.io.decode_image
tf.io.decode_image(
contents, channels=None, dtype=tf.dtypes.uint8, name=None,
expand_animations=True
)
Detects whether an image is a BMP, GIF, JPEG, or PNG, and performs the appropriate operation to convert the input bytes string into a Tensor of type dtype.
Note: decode_gif returns a 4-D array [num_frames, height, width, 3], as opposed to decode_bmp, decode_jpeg and decode_png, which return 3-D arrays [height, width, num_channels]. Make sure to take this into account when constructing your graph if you are intermixing GIF files with BMP, JPEG, and/or PNG files. Alternately, set the expand_animations argument of this function to False, in which case the op will return 3-dimensional tensors and will truncate animated GIF files to the first frame.
Note: If the first frame of an animated GIF does not occupy the entire canvas (maximum frame width x maximum frame height), then it fills the unoccupied areas (in the first frame) with zeros (black). For frames after the first frame that does not occupy the entire canvas, it uses the previous frame to fill the unoccupied areas.
Args
contents 0-D string. The encoded image bytes.
channels An optional int. Defaults to 0. Number of color channels for the decoded image.
dtype The desired DType of the returned Tensor.
name A name for the operation (optional)
expand_animations Controls the shape of the returned op's output. If True, the returned op will produce a 3-D tensor for PNG, JPEG, and BMP files; and a 4-D tensor for all GIFs, whether animated or not. If, False, the returned op will produce a 3-D tensor for all file types and will truncate animated GIFs to the first frame.
Returns Tensor with type dtype and a 3- or 4-dimensional shape, depending on the file type and the value of the expand_animations parameter.
Raises
ValueError On incorrect number of channels. | tensorflow.io.decode_image |
tf.io.decode_jpeg Decode a JPEG-encoded image to a uint8 tensor. View aliases Main aliases
tf.image.decode_jpeg Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_jpeg, tf.compat.v1.io.decode_jpeg
tf.io.decode_jpeg(
contents, channels=0, ratio=1, fancy_upscaling=True,
try_recover_truncated=False, acceptable_fraction=1, dct_method='',
name=None
)
The attr channels indicates the desired number of color channels for the decoded image. Accepted values are: 0: Use the number of channels in the JPEG-encoded image. 1: output a grayscale image. 3: output an RGB image. If needed, the JPEG-encoded image is transformed to match the requested number of color channels. The attr ratio allows downscaling the image by an integer factor during decoding. Allowed values are: 1, 2, 4, and 8. This is much faster than downscaling the image later. This op also supports decoding PNGs and non-animated GIFs since the interface is the same, though it is cleaner to use tf.io.decode_image.
Args
contents A Tensor of type string. 0-D. The JPEG-encoded image.
channels An optional int. Defaults to 0. Number of color channels for the decoded image.
ratio An optional int. Defaults to 1. Downscaling ratio.
fancy_upscaling An optional bool. Defaults to True. If true use a slower but nicer upscaling of the chroma planes (yuv420/422 only).
try_recover_truncated An optional bool. Defaults to False. If true try to recover an image from truncated input.
acceptable_fraction An optional float. Defaults to 1. The minimum required fraction of lines before a truncated input is accepted.
dct_method An optional string. Defaults to "". string specifying a hint about the algorithm used for decompression. Defaults to "" which maps to a system-specific default. Currently valid values are ["INTEGER_FAST", "INTEGER_ACCURATE"]. The hint may be ignored (e.g., the internal jpeg library changes to a version that does not have that specific option.)
name A name for the operation (optional).
Returns A Tensor of type uint8. | tensorflow.io.decode_jpeg |
tf.io.decode_json_example Convert JSON-encoded Example records to binary protocol buffer strings. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.decode_json_example, tf.compat.v1.io.decode_json_example
tf.io.decode_json_example(
json_examples, name=None
)
This op translates a tensor containing Example records, encoded using the standard JSON mapping, into a tensor containing the same records encoded as binary protocol buffers. The resulting tensor can then be fed to any of the other Example-parsing ops.
Args
json_examples A Tensor of type string. Each string is a JSON object serialized according to the JSON mapping of the Example proto.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.decode_json_example |
tf.io.decode_png Decode a PNG-encoded image to a uint8 or uint16 tensor. View aliases Main aliases
tf.image.decode_png Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.decode_png, tf.compat.v1.io.decode_png
tf.io.decode_png(
contents, channels=0, dtype=tf.dtypes.uint8, name=None
)
The attr channels indicates the desired number of color channels for the decoded image. Accepted values are: 0: Use the number of channels in the PNG-encoded image. 1: output a grayscale image. 3: output an RGB image. 4: output an RGBA image. If needed, the PNG-encoded image is transformed to match the requested number of color channels. This op also supports decoding JPEGs and non-animated GIFs since the interface is the same, though it is cleaner to use tf.io.decode_image.
Args
contents A Tensor of type string. 0-D. The PNG-encoded image.
channels An optional int. Defaults to 0. Number of color channels for the decoded image.
dtype An optional tf.DType from: tf.uint8, tf.uint16. Defaults to tf.uint8.
name A name for the operation (optional).
Returns A Tensor of type dtype. | tensorflow.io.decode_png |
tf.io.decode_proto The op extracts fields from a serialized protocol buffers message into tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.decode_proto
tf.io.decode_proto(
bytes, message_type, field_names, output_types,
descriptor_source='local://', message_format='binary',
sanitize=False, name=None
)
The decode_proto op extracts fields from a serialized protocol buffers message into tensors. The fields in field_names are decoded and converted to the corresponding output_types if possible. A message_type name must be provided to give context for the field names. The actual message descriptor can be looked up either in the linked-in descriptor pool or a filename provided by the caller using the descriptor_source attribute. Each output tensor is a dense tensor. This means that it is padded to hold the largest number of repeated elements seen in the input minibatch. (The shape is also padded by one to prevent zero-sized dimensions). The actual repeat counts for each example in the minibatch can be found in the sizes output. In many cases the output of decode_proto is fed immediately into tf.squeeze if missing values are not a concern. When using tf.squeeze, always pass the squeeze dimension explicitly to avoid surprises. For the most part, the mapping between Proto field types and TensorFlow dtypes is straightforward. However, there are a few special cases: A proto field that contains a submessage or group can only be converted to DT_STRING (the serialized submessage). This is to reduce the complexity of the API. The resulting string can be used as input to another instance of the decode_proto op. TensorFlow lacks support for unsigned integers. The ops represent uint64 types as a DT_INT64 with the same twos-complement bit pattern (the obvious way). Unsigned int32 values can be represented exactly by specifying type DT_INT64, or using twos-complement if the caller specifies DT_INT32 in the output_types attribute. Both binary and text proto serializations are supported, and can be chosen using the format attribute. The descriptor_source attribute selects the source of protocol descriptors to consult when looking up message_type. This may be: An empty string or "local://", in which case protocol descriptors are created for C++ (not Python) proto definitions linked to the binary. A file, in which case protocol descriptors are created from the file, which is expected to contain a FileDescriptorSet serialized as a string. NOTE: You can build a descriptor_source file using the --descriptor_set_out and --include_imports options to the protocol compiler protoc. A "bytes://", in which protocol descriptors are created from <bytes>, which is expected to be a FileDescriptorSet serialized as a string.
Args
bytes A Tensor of type string. Tensor of serialized protos with shape batch_shape.
message_type A string. Name of the proto message type to decode.
field_names A list of strings. List of strings containing proto field names. An extension field can be decoded by using its full name, e.g. EXT_PACKAGE.EXT_FIELD_NAME.
output_types A list of tf.DTypes. List of TF types to use for the respective field in field_names.
descriptor_source An optional string. Defaults to "local://". Either the special value local:// or a path to a file containing a serialized FileDescriptorSet.
message_format An optional string. Defaults to "binary". Either binary or text.
sanitize An optional bool. Defaults to False. Whether to sanitize the result or not.
name A name for the operation (optional).
Returns A tuple of Tensor objects (sizes, values). sizes A Tensor of type int32.
values A list of Tensor objects of type output_types. | tensorflow.io.decode_proto |
tf.io.decode_raw Convert raw byte strings into tensors.
tf.io.decode_raw(
input_bytes, out_type, little_endian=True, fixed_length=None, name=None
)
Args
input_bytes Each element of the input Tensor is converted to an array of bytes.
out_type DType of the output. Acceptable types are half, float, double, int32, uint16, uint8, int16, int8, int64.
little_endian Whether the input_bytes data is in little-endian format. Data will be converted into host byte order if necessary.
fixed_length If set, the first fixed_length bytes of each element will be converted. Data will be zero-padded or truncated to the specified length. fixed_length must be a multiple of the size of out_type. fixed_length must be specified if the elements of input_bytes are of variable length.
name A name for the operation (optional).
Returns A Tensor object storing the decoded bytes. | tensorflow.io.decode_raw |
tf.io.deserialize_many_sparse View source on GitHub Deserialize and concatenate SparseTensors from a serialized minibatch. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.deserialize_many_sparse, tf.compat.v1.io.deserialize_many_sparse
tf.io.deserialize_many_sparse(
serialized_sparse, dtype, rank=None, name=None
)
The input serialized_sparse must be a string matrix of shape [N x 3] where N is the minibatch size and the rows correspond to packed outputs of serialize_sparse. The ranks of the original SparseTensor objects must all match. When the final SparseTensor is created, it has rank one higher than the ranks of the incoming SparseTensor objects (they have been concatenated along a new row dimension). The output SparseTensor object's shape values for all dimensions but the first are the max across the input SparseTensor objects' shape values for the corresponding dimensions. Its first shape value is N, the minibatch size. The input SparseTensor objects' indices are assumed ordered in standard lexicographic order. If this is not the case, after this step run sparse.reorder to restore index ordering. For example, if the serialized input is a [2, 3] matrix representing two original SparseTensor objects: index = [ 0]
[10]
[20]
values = [1, 2, 3]
shape = [50]
and index = [ 2]
[10]
values = [4, 5]
shape = [30]
then the final deserialized SparseTensor will be: index = [0 0]
[0 10]
[0 20]
[1 2]
[1 10]
values = [1, 2, 3, 4, 5]
shape = [2 50]
Args
serialized_sparse 2-D Tensor of type string of shape [N, 3]. The serialized and packed SparseTensor objects.
dtype The dtype of the serialized SparseTensor objects.
rank (optional) Python int, the rank of the SparseTensor objects.
name A name prefix for the returned tensors (optional)
Returns A SparseTensor representing the deserialized SparseTensors, concatenated along the SparseTensors' first dimension. All of the serialized SparseTensors must have had the same rank and type. | tensorflow.io.deserialize_many_sparse |
tf.io.encode_base64 Encode strings into web-safe base64 format. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.encode_base64, tf.compat.v1.io.encode_base64
tf.io.encode_base64(
input, pad=False, name=None
)
Refer to the following article for more information on base64 format: en.wikipedia.org/wiki/Base64. Base64 strings may have padding with '=' at the end so that the encoded has length multiple of 4. See Padding section of the link above. Web-safe means that the encoder uses - and _ instead of + and /.
Args
input A Tensor of type string. Strings to be encoded.
pad An optional bool. Defaults to False. Bool whether padding is applied at the ends.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.encode_base64 |
tf.io.encode_jpeg JPEG-encode an image. View aliases Main aliases
tf.image.encode_jpeg Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.encode_jpeg, tf.compat.v1.io.encode_jpeg
tf.io.encode_jpeg(
image, format='', quality=95, progressive=False, optimize_size=False,
chroma_downsampling=True, density_unit='in', x_density=300,
y_density=300, xmp_metadata='', name=None
)
image is a 3-D uint8 Tensor of shape [height, width, channels]. The attr format can be used to override the color format of the encoded output. Values can be:
'': Use a default format based on the number of channels in the image.
grayscale: Output a grayscale JPEG image. The channels dimension of image must be 1.
rgb: Output an RGB JPEG image. The channels dimension of image must be 3. If format is not specified or is the empty string, a default format is picked in function of the number of channels in image: 1: Output a grayscale image. 3: Output an RGB image.
Args
image A Tensor of type uint8. 3-D with shape [height, width, channels].
format An optional string from: "", "grayscale", "rgb". Defaults to "". Per pixel image format.
quality An optional int. Defaults to 95. Quality of the compression from 0 to 100 (higher is better and slower).
progressive An optional bool. Defaults to False. If True, create a JPEG that loads progressively (coarse to fine).
optimize_size An optional bool. Defaults to False. If True, spend CPU/RAM to reduce size with no quality change.
chroma_downsampling An optional bool. Defaults to True. See http://en.wikipedia.org/wiki/Chroma_subsampling
density_unit An optional string from: "in", "cm". Defaults to "in". Unit used to specify x_density and y_density: pixels per inch ('in') or centimeter ('cm').
x_density An optional int. Defaults to 300. Horizontal pixels per density unit.
y_density An optional int. Defaults to 300. Vertical pixels per density unit.
xmp_metadata An optional string. Defaults to "". If not empty, embed this XMP metadata in the image header.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.encode_jpeg |
tf.io.encode_png PNG-encode an image. View aliases Main aliases
tf.image.encode_png Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.encode_png, tf.compat.v1.io.encode_png
tf.io.encode_png(
image, compression=-1, name=None
)
image is a 3-D uint8 or uint16 Tensor of shape [height, width, channels] where channels is: 1: for grayscale. 2: for grayscale + alpha. 3: for RGB. 4: for RGBA. The ZLIB compression level, compression, can be -1 for the PNG-encoder default or a value from 0 to 9. 9 is the highest compression level, generating the smallest output, but is slower.
Args
image A Tensor. Must be one of the following types: uint8, uint16. 3-D with shape [height, width, channels].
compression An optional int. Defaults to -1. Compression level.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.encode_png |
tf.io.encode_proto The op serializes protobuf messages provided in the input tensors. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.encode_proto
tf.io.encode_proto(
sizes, values, field_names, message_type,
descriptor_source='local://', name=None
)
The types of the tensors in values must match the schema for the fields specified in field_names. All the tensors in values must have a common shape prefix, batch_shape. The sizes tensor specifies repeat counts for each field. The repeat count (last dimension) of a each tensor in values must be greater than or equal to corresponding repeat count in sizes. A message_type name must be provided to give context for the field names. The actual message descriptor can be looked up either in the linked-in descriptor pool or a filename provided by the caller using the descriptor_source attribute. For the most part, the mapping between Proto field types and TensorFlow dtypes is straightforward. However, there are a few special cases: A proto field that contains a submessage or group can only be converted to DT_STRING (the serialized submessage). This is to reduce the complexity of the API. The resulting string can be used as input to another instance of the decode_proto op. TensorFlow lacks support for unsigned integers. The ops represent uint64 types as a DT_INT64 with the same twos-complement bit pattern (the obvious way). Unsigned int32 values can be represented exactly by specifying type DT_INT64, or using twos-complement if the caller specifies DT_INT32 in the output_types attribute. The descriptor_source attribute selects the source of protocol descriptors to consult when looking up message_type. This may be: An empty string or "local://", in which case protocol descriptors are created for C++ (not Python) proto definitions linked to the binary. A file, in which case protocol descriptors are created from the file, which is expected to contain a FileDescriptorSet serialized as a string. NOTE: You can build a descriptor_source file using the --descriptor_set_out and --include_imports options to the protocol compiler protoc. A "bytes://", in which protocol descriptors are created from <bytes>, which is expected to be a FileDescriptorSet serialized as a string.
Args
sizes A Tensor of type int32. Tensor of int32 with shape [batch_shape, len(field_names)].
values A list of Tensor objects. List of tensors containing values for the corresponding field.
field_names A list of strings. List of strings containing proto field names.
message_type A string. Name of the proto message type to decode.
descriptor_source An optional string. Defaults to "local://".
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.encode_proto |
tf.io.extract_jpeg_shape Extract the shape information of a JPEG-encoded image. View aliases Main aliases
tf.image.extract_jpeg_shape Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.extract_jpeg_shape, tf.compat.v1.io.extract_jpeg_shape
tf.io.extract_jpeg_shape(
contents, output_type=tf.dtypes.int32, name=None
)
This op only parses the image header, so it is much faster than DecodeJpeg.
Args
contents A Tensor of type string. 0-D. The JPEG-encoded image.
output_type An optional tf.DType from: tf.int32, tf.int64. Defaults to tf.int32. (Optional) The output type of the operation (int32 or int64). Defaults to int32.
name A name for the operation (optional).
Returns A Tensor of type output_type. | tensorflow.io.extract_jpeg_shape |
tf.io.FixedLenFeature View source on GitHub Configuration for parsing a fixed-length input feature. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.FixedLenFeature, tf.compat.v1.io.FixedLenFeature
tf.io.FixedLenFeature(
shape, dtype, default_value=None
)
To treat sparse input as dense, provide a default_value; otherwise, the parse functions will fail on any examples missing this feature. Fields:
shape: Shape of input data.
dtype: Data type of input.
default_value: Value to be used if an example is missing this feature. It must be compatible with dtype and of the specified shape.
Attributes
shape
dtype
default_value | tensorflow.io.fixedlenfeature |
tf.io.FixedLenSequenceFeature View source on GitHub Configuration for parsing a variable-length input feature into a Tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.FixedLenSequenceFeature, tf.compat.v1.io.FixedLenSequenceFeature
tf.io.FixedLenSequenceFeature(
shape, dtype, allow_missing=False, default_value=None
)
The resulting Tensor of parsing a single SequenceExample or Example has a static shape of [None] + shape and the specified dtype. The resulting Tensor of parsing a batch_size many Examples has a static shape of [batch_size, None] + shape and the specified dtype. The entries in the batch from different Examples will be padded with default_value to the maximum length present in the batch. To treat a sparse input as dense, provide allow_missing=True; otherwise, the parse functions will fail on any examples missing this feature. Fields:
shape: Shape of input data for dimension 2 and higher. First dimension is of variable length None.
dtype: Data type of input.
allow_missing: Whether to allow this feature to be missing from a feature list item. Is available only for parsing SequenceExample not for parsing Examples.
default_value: Scalar value to be used to pad multiple Examples to their maximum length. Irrelevant for parsing a single Example or SequenceExample. Defaults to "" for dtype string and 0 otherwise (optional).
Attributes
shape
dtype
allow_missing
default_value | tensorflow.io.fixedlensequencefeature |
Module: tf.io.gfile Public API for tf.io.gfile namespace. Classes class GFile: File I/O wrappers without thread locking. Functions copy(...): Copies data from src to dst. exists(...): Determines whether a path exists or not. glob(...): Returns a list of files that match the given pattern(s). isdir(...): Returns whether the path is a directory or not. listdir(...): Returns a list of entries contained within a directory. makedirs(...): Creates a directory and all parent/intermediate directories. mkdir(...): Creates a directory with the name given by path. remove(...): Deletes the path located at 'path'. rename(...): Rename or move a file / directory. rmtree(...): Deletes everything under path recursively. stat(...): Returns file statistics for a given path. walk(...): Recursive directory tree generator for directories. | tensorflow.io.gfile |
tf.io.gfile.copy View source on GitHub Copies data from src to dst. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.copy
tf.io.gfile.copy(
src, dst, overwrite=False
)
Args
src string, name of the file whose contents need to be copied
dst string, name of the file to which to copy to
overwrite boolean, if false it's an error for dst to be occupied by an existing file.
Raises
errors.OpError If the operation fails. | tensorflow.io.gfile.copy |
tf.io.gfile.exists View source on GitHub Determines whether a path exists or not. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.exists
tf.io.gfile.exists(
path
)
Args
path string, a path
Returns True if the path exists, whether it's a file or a directory. False if the path does not exist and there are no filesystem errors.
Raises
errors.OpError Propagates any errors reported by the FileSystem API. | tensorflow.io.gfile.exists |
tf.io.gfile.GFile View source on GitHub File I/O wrappers without thread locking. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.gfile.GFile, tf.compat.v1.gfile.Open, tf.compat.v1.io.gfile.GFile
tf.io.gfile.GFile(
name, mode='r'
)
The main roles of the tf.io.gfile module are: To provide an API that is close to Python's file I/O objects, and To provide an implementation based on TensorFlow's C++ FileSystem API. The C++ FileSystem API supports multiple file system implementations, including local files, Google Cloud Storage (using a gs:// prefix, and HDFS (using an hdfs:// prefix). TensorFlow exports these as tf.io.gfile, so that you can use these implementations for saving and loading checkpoints, writing to TensorBoard logs, and accessing training data (among other uses). However, if all your files are local, you can use the regular Python file API without any problem.
Note: though similar to Python's I/O implementation, there are semantic differences to make tf.io.gfile more efficient for backing filesystems. For example, a write mode file will not be opened until the first write call, to minimize RPC invocations in network filesystems.
Attributes
mode Returns the mode in which the file was opened.
name Returns the file name. Methods close View source
close()
Closes FileIO. Should be called for the WritableFile to be flushed. flush View source
flush()
Flushes the Writable file. This only ensures that the data has made its way out of the process without any guarantees on whether it's written to disk. This means that the data would survive an application crash but not necessarily an OS crash. next View source
next()
read View source
read(
n=-1
)
Returns the contents of a file as a string. Starts reading from current position in file.
Args
n Read n bytes if n != -1. If n = -1, reads to end of file.
Returns n bytes of the file (or whole file) in bytes mode or n bytes of the string if in string (regular) mode.
readline View source
readline()
Reads the next line, keeping \n. At EOF, returns ''. readlines View source
readlines()
Returns all lines from the file in a list. seek View source
seek(
offset=None, whence=0, position=None
)
Seeks to the offset in the file. (deprecated arguments) Warning: SOME ARGUMENTS ARE DEPRECATED: (position). They will be removed in a future version. Instructions for updating: position is deprecated in favor of the offset argument.
Args
offset The byte count relative to the whence argument.
whence Valid values for whence are: 0: start of the file (default) 1: relative to the current position of the file 2: relative to the end of file. offset is usually negative. seekable View source
seekable()
Returns True as FileIO supports random access ops of seek()/tell() size View source
size()
Returns the size of the file. tell View source
tell()
Returns the current position in the file. write View source
write(
file_content
)
Writes file_content to the file. Appends to the end of the file. __enter__ View source
__enter__()
Make usable with "with" statement. __exit__ View source
__exit__(
unused_type, unused_value, unused_traceback
)
Make usable with "with" statement. __iter__ View source
__iter__() | tensorflow.io.gfile.gfile |
tf.io.gfile.glob View source on GitHub Returns a list of files that match the given pattern(s). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.glob
tf.io.gfile.glob(
pattern
)
The patterns are defined as strings. Supported patterns are defined here. Note that the pattern can be a Python iteratable of string patterns. The format definition of the pattern is: pattern: { term } term:
'*': matches any sequence of non-'/' characters
'?': matches a single non-'/' character
'[' [ '^' ] { match-list } ']': matches any single character (not) on the list
c: matches character c where c != '*', '?', '\\', '['
'\\' c: matches character c
character range:
c: matches character c while c != '\\', '-', ']'
'\\' c: matches character c
lo '-' hi: matches character c for lo <= c <= hi
Examples:
tf.io.gfile.glob("*.py")
# For example, ['__init__.py']
tf.io.gfile.glob("__init__.??")
# As above
files = {"*.py"}
the_iterator = iter(files)
tf.io.gfile.glob(the_iterator)
# As above
See the C++ function GetMatchingPaths in core/platform/file_system.h for implementation details.
Args
pattern string or iterable of strings. The glob pattern(s).
Returns A list of strings containing filenames that match the given pattern(s).
Raises
errors.OpError If there are filesystem / directory listing errors.
errors.NotFoundError If pattern to be matched is an invalid directory. | tensorflow.io.gfile.glob |
tf.io.gfile.isdir View source on GitHub Returns whether the path is a directory or not. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.isdir
tf.io.gfile.isdir(
path
)
Args
path string, path to a potential directory
Returns True, if the path is a directory; False otherwise | tensorflow.io.gfile.isdir |
tf.io.gfile.listdir View source on GitHub Returns a list of entries contained within a directory. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.listdir
tf.io.gfile.listdir(
path
)
The list is in arbitrary order. It does not contain the special entries "." and "..".
Args
path string, path to a directory
Returns [filename1, filename2, ... filenameN] as strings
Raises errors.NotFoundError if directory doesn't exist | tensorflow.io.gfile.listdir |
tf.io.gfile.makedirs View source on GitHub Creates a directory and all parent/intermediate directories. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.makedirs
tf.io.gfile.makedirs(
path
)
It succeeds if path already exists and is writable.
Args
path string, name of the directory to be created
Raises
errors.OpError If the operation fails. | tensorflow.io.gfile.makedirs |
tf.io.gfile.mkdir View source on GitHub Creates a directory with the name given by path. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.mkdir
tf.io.gfile.mkdir(
path
)
Args
path string, name of the directory to be created Notes: The parent directories need to exist. Use tf.io.gfile.makedirs instead if there is the possibility that the parent dirs don't exist.
Raises
errors.OpError If the operation fails. | tensorflow.io.gfile.mkdir |
tf.io.gfile.remove View source on GitHub Deletes the path located at 'path'. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.remove
tf.io.gfile.remove(
path
)
Args
path string, a path
Raises
errors.OpError Propagates any errors reported by the FileSystem API. E.g., NotFoundError if the path does not exist. | tensorflow.io.gfile.remove |
tf.io.gfile.rename View source on GitHub Rename or move a file / directory. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.rename
tf.io.gfile.rename(
src, dst, overwrite=False
)
Args
src string, pathname for a file
dst string, pathname to which the file needs to be moved
overwrite boolean, if false it's an error for dst to be occupied by an existing file.
Raises
errors.OpError If the operation fails. | tensorflow.io.gfile.rename |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.