[英]TensorFlow Resize image tensor to dynamic shape
我试图用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_height
和new_width
传递给tf.image.resize_images(...)
因为其中一个是张量, resize_images
需要整数作为高度和宽度输入。
有没有办法“拉出”张量的整数,还是有其他方法可以用TensorFlow完成我的任务?
提前致谢。
编辑
由于我还有一些 tf.image.resize_images
其他问题 ,这里的代码对我tf.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])
这样做的方法是使用(目前是实验性的,但在下一版本中可用) 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_height
和new_width
Tensor
值,它们将在运行时获取适当的值。
*要在当前发布的版本中访问操作员,您需要导入以下内容:
from tensorflow.python.ops import control_flow_ops
...然后使用control_flow_ops.cond()
而不是tf.cond()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.