tf.keras.ops.saturate_cast

Performs a safe saturating cast to the desired dtype.

Saturating cast prevents data type overflow when casting to dtype with smaller values range. E.g. ops.cast(ops.cast([-1, 256], "float32"), "uint8") returns [255, 0], but ops.saturate_cast(ops.cast([-1, 256], "float32"), "uint8") returns [0, 255].

x A tensor or variable.
dtype The target type.

A safely casted tensor of the specified dtype.

Example:

Image resizing with bicubic interpolation may produce values outside original range.

>>> image2x2 = np.array([0, 1, 254, 255], dtype="uint8").reshape(1, 2, 2, 1)
>>> image4x4 = tf.image.resize(image2x2, (4, 4), method="bicubic")
>>> print(image4x4.numpy().squeeze())
>>> # [[-22.500004 -22.204624 -21.618908 -21.32353 ]
>>> #  [ 52.526054  52.82143   53.407146  53.70253 ]
>>> #  [201.29752  201.59288  202.17859  202.47395 ]
>>> #  [276.32355  276.61893  277.20465  277.50006 ]]

Casting this resized image back to uint8 will cause overflow.

>>> image4x4_casted = ops.cast(image4x4, "uint8")
>>> print(image4x4_casted.numpy().squeeze())
>>> # [[234 234 235 235]
>>> #  [ 52  52  53  53]
>>> #  [201 201 202 202]
>>> #  [ 20  20  21  21]]

Saturate casting to uint8 will clip values to uint8 range before casting and will not cause overflow.

>>> image4x4_saturate_casted = ops.saturate_cast(image4x4, "uint8")
>>> print(image4x4_saturate_casted.numpy().squeeze())
>>> # [[  0   0   0   0]
>>> #  [ 52  52  53  53]
>>> #  [201 201 202 202]
>>> #  [255 255 255 255]]