簡體   English   中英

在 Tensorflow 中調整圖像保留縱橫比的大小

[英]Resize image preserving aspect ratio in Tensorflow

我對 TF 相當陌生。 我正在嘗試調整圖像張量的大小,以便圖像的最低維度是恆定值 LO_DIM。 在非 tf 環境中,我只會做這樣的事情:

if img.size[0] < img.size[1]:
    h = int(float(LO_DIM * img.size[1]) / img.size[0])
    img = resize(img, [LO_DIM, h])
else:
    w = int(float(LO_DIM * img.size[0]) / img.size[1])
    img = resize(img, [w, LO_DIM])

我知道,要調整大小,我應該使用tf.image.resize_images ,但考慮到張量似乎具有shape=<unknown> ,我不確定如何計算新的wh

注意:我傳遞的每個圖像可能有不同的大小,這就是我需要動態計算它的原因。 我使用 LO_DIM 來保持縱橫比而不是扭曲圖像。

關於如何實現這一目標的任何建議?

如果有幫助,處理目標是從縮放后的圖像中獲得一個隨機的 NxN 補丁,但我能找到的只是resize_image_with_crop_or_pad ,它似乎沒有進行初始縮放。

這是由這個問題回答的。

這是調整張量圖像大小保持 aspext 比率的示例片段:

def resize_image_keep_aspect(image, lo_dim=LO_DIM):
  # Take width/height
  initial_width = tf.shape(image)[0]
  initial_height = tf.shape(image)[1]

  # Take the greater value, and use it for the ratio
  min_ = tf.minimum(initial_width, initial_height)
  ratio = tf.to_float(min_) / tf.constant(lo_dim, dtype=tf.float32)

  new_width = tf.to_int32(tf.to_float(initial_width) / ratio)
  new_height = tf.to_int32(tf.to_float(initial_height) / ratio)

  return tf.image.resize_images(image, [new_width, new_height])

具有shape=<unknown>張量的問題通過使用類型tf.image.decode_jpeg解碼器(如tf.image.decode_jpegtf.image.decode_png ,而不是tf.image.decode_imagetf.image.decode_image

Tensorflow 2.x 有一個內置方法來實現相同的結果。

默認方法用法:

import tensorflow as tf
tf.image.resize(
    images, size, method=ResizeMethod.BILINEAR, preserve_aspect_ratio=False,
    antialias=False, name=None
)

示例用法:

>>> max_10_20 = tf.image.resize(image, [10,20], preserve_aspect_ratio=True)
>>> max_10_20.shape.as_list()
[1, 10, 10, 1]

preserve_aspect_ratio標志執行以下操作:

  • 確定是否保留縱橫比。
  • 如果設置了該標志,則圖像將調整為適合尺寸的尺寸,同時保留原始圖像的縱橫比。
  • 如果尺寸大於圖像的當前尺寸,則放大圖像。

來源: https : //www.tensorflow.org/api_docs/python/tf/image/resize

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM