代码之家  ›  专栏  ›  技术社区  ›  kuranes

在Tensorflow中调整图像大小以保持纵横比

  •  3
  • kuranes  · 技术社区  · 8 年前

    我是TF的新手。我正在尝试调整图像张量的大小,以便图像的最低维度为LO\u 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 ,但我不确定如何计算新的 w h 考虑到张量似乎 shape=<unknown> .

    注意:我传递的每个图像可能有不同的大小,这就是为什么我需要动态计算它。我使用LO\u DIM来保持纵横比,并且不会扭曲图像。

    对如何实现这一目标有何建议?

    如果有帮助的话,处理的目标是从缩放的图像中获得一个随机的NxN面片,但我能找到的只是 resize_image_with_crop_or_pad 这似乎不能进行初始缩放。

    2 回复  |  直到 8 年前
        1
  •  6
  •   kuranes    8 年前

    这就是答案 issue .

    下面是一个示例片段,用于调整tensor图像的大小以保持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_png ,而不是 tf.image.decode_image

        2
  •  0
  •   Animikh Aich    5 年前

    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 flag执行以下操作:

    • 确定是否保留纵横比。
    • 如果设置了该标志,则图像大小将调整为适合大小的大小,同时保留原始图像的纵横比。
    • 如果大小大于图像的当前大小,请放大图像。

    资料来源: https://www.tensorflow.org/api_docs/python/tf/image/resize

    推荐文章