【问题标题】:TensorFlow Resize image tensor to dynamic shapeTensorFlow 将图像张量大小调整为动态形状
【发布时间】:2016-05-14 12:37:31
【问题描述】:

我正在尝试使用 TensorFlow 读取一些图像输入以解决图像分类问题。

当然,我正在使用tf.image.decode_jpeg(...) 进行此操作。我的图像大小可变,因此我无法为图像张量指定固定形状。

但我需要根据图像的实际大小来缩放图像。具体来说,我想以保留纵横比的方式将短边缩放为固定值,将长边缩放为固定值。

我可以通过shape = tf.shape(image)得到某个图像的实际形状。我也可以像

这样计算新的更长的边缘
shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_shorter_edge = 400
if height <= width:
    new_height = new_shorter_edge
    new_width = ((width / height) * new_shorter_edge)
else:
    new_width = new_shorter_edge
    new_height = ((height / width) * new_shorter_edge)

我现在的问题是我不能将new_heightnew_width 传递给tf.image.resize_images(...),因为其中一个是张量,而resize_images 需要整数作为高度和宽度输入。

有没有办法“拉出”张量的整数,或者有没有其他方法可以用 TensorFlow 完成我的任务?

提前致谢。


编辑

因为我也有 some other issuestf.image.resize_images,所以下面是对我有用的代码:

shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_shorter_edge = tf.constant(400, dtype=tf.int32)

height_smaller_than_width = tf.less_equal(height, width)
new_height_and_width = tf.cond(
    height_smaller_than_width,
    lambda: (new_shorter_edge, _compute_longer_edge(height, width, new_shorter_edge)),
    lambda: (_compute_longer_edge(width, height, new_shorter_edge), new_shorter_edge)
)

image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, tf.pack(new_height_and_width))
image = tf.squeeze(image, [0])

【问题讨论】:

    标签: python image shape tensorflow


    【解决方案1】:

    执行此操作的方法是使用(目前是实验性的,但在下一版本中可用)tf.cond()* 运算符。此运算符能够测试在运行时计算的值,并根据该值执行两个分支之一。

    shape = tf.shape(image)
    height = shape[0]
    width = shape[1]
    new_shorter_edge = 400
    height_smaller_than_width = tf.less_equal(height, width)
    
    new_shorter_edge = tf.constant(400)
    new_height, new_width = tf.cond(
        height_smaller_than_width,
        lambda: new_shorter_edge, (width / height) * new_shorter_edge,
        lambda: new_shorter_edge, (height / width) * new_shorter_edge)
    

    现在您有了new_heightnew_widthTensor 值,它们将在运行时采用适当的值。


    * 要访问当前发布版本中的运算符,您需要导入以下内容:

    from tensorflow.python.ops import control_flow_ops
    

    ...然后使用control_flow_ops.cond() 而不是tf.cond()

    【讨论】:

    • 这个功能非常好,很酷。但我的问题仍然存在。 tf.image.resize_images(...)int32 作为第二个和第三个参数。这就是new_heightnew_width 的值应该去的地方。在我对 TensorFlow 的理解中,对 eval() 的调用将不起作用,因为这只在运行时进行评估。是否有任何命令告诉 TensorFlow 在图形构建时“提取张量的第一个(也是唯一一个)整数”?
    • 调用tf.image.resize_images(image, new_height, new_width) 总是抛出TypeError: Expected int32, got list containing Tensors of type '_Message' instead.
    • 啊,这对我来说似乎是一个错误。我提交了an issue,并会尽快修复。
    • 我看到你已经修好了。非常感谢,这对我真的很有帮助:)
    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多