將圖像大小調整為目標大小,而不會出現縱橫比失真。
用法
tf.keras.preprocessing.image.smart_resize(
x, size, interpolation='bilinear'
)
參數
-
x
輸入圖像或一批圖像(作為張量或 NumPy 數組)。格式必須為(height, width, channels)
或(batch_size, height, width, channels)
。 -
size
(height, width)
整數的元組。目標大小。 -
interpolation
字符串,用於調整大小的插值。默認為'bilinear'
。支持bilinear
,nearest
,bicubic
,area
,lanczos3
,lanczos5
,gaussian
,mitchellcubic
。
返回
-
形狀為
(size[0], size[1], channels)
的數組。如果輸入圖像是 NumPy 數組,則輸出是 NumPy 數組,如果是 TF 張量,則輸出是 TF 張量。
TensorFlow 圖像數據集通常會生成大小不同的圖像。但是,這些圖像需要進行批處理才能被 Keras 層處理。要進行批處理,圖像需要共享相同的高度和寬度。
你可以簡單地做:
size = (200, 200)
ds = ds.map(lambda img:tf.image.resize(img, size))
但是,如果這樣做,則會扭曲圖像的縱橫比,因為通常它們的縱橫比並不都與 size
相同。在許多情況下這很好,但並非總是如此(例如,對於 GAN,這可能是一個問題)。
請注意,將參數 preserve_aspect_ratio=True
傳遞給 resize
將保留縱橫比,但代價是不再遵守提供的目標大小。因為tf.image.resize
不會裁剪圖像,所以您的輸出圖像仍然會有不同的大小。
這要求:
size = (200, 200)
ds = ds.map(lambda img:smart_resize(img, size))
您的輸出圖像實際上是 (200, 200)
,並且不會失真。相反,圖像中不適合目標尺寸的部分會被裁剪掉。
調整大小的過程是:
- 取與目標尺寸具有相同縱橫比的圖像的最大居中裁剪。例如,如果
size=(200, 200)
並且輸入圖像的大小為(340, 500)
,我們將沿寬度居中裁剪(340, 340)
。 - 將裁剪後的圖像調整為目標大小。在上麵的示例中,我們將
(340, 340)
裁剪調整為(200, 200)
。
相關用法
- Python tf.keras.preprocessing.image.ImageDataGenerator用法及代碼示例
- Python tf.keras.preprocessing.image.DirectoryIterator.__len__用法及代碼示例
- Python tf.keras.preprocessing.sequence.TimeseriesGenerator用法及代碼示例
- Python tf.keras.preprocessing.sequence.pad_sequences用法及代碼示例
- Python tf.keras.preprocessing.sequence.make_sampling_table用法及代碼示例
- Python tf.keras.preprocessing.text.text_to_word_sequence用法及代碼示例
- Python tf.keras.applications.inception_resnet_v2.preprocess_input用法及代碼示例
- Python tf.keras.metrics.Mean.merge_state用法及代碼示例
- Python tf.keras.layers.InputLayer用法及代碼示例
- Python tf.keras.callbacks.ReduceLROnPlateau用法及代碼示例
- Python tf.keras.layers.serialize用法及代碼示例
- Python tf.keras.metrics.Hinge用法及代碼示例
- Python tf.keras.experimental.WideDeepModel.compute_loss用法及代碼示例
- Python tf.keras.metrics.SparseCategoricalAccuracy.merge_state用法及代碼示例
- Python tf.keras.metrics.RootMeanSquaredError用法及代碼示例
- Python tf.keras.applications.resnet50.preprocess_input用法及代碼示例
- Python tf.keras.metrics.SparseCategoricalCrossentropy.merge_state用法及代碼示例
- Python tf.keras.metrics.sparse_categorical_accuracy用法及代碼示例
- Python tf.keras.layers.Dropout用法及代碼示例
- Python tf.keras.activations.softplus用法及代碼示例
注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.keras.preprocessing.image.smart_resize。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。