我正在尝试使用 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 完成我的任务?
提前致谢。
编辑
因为我也有 some other issues使用 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()
* 运算符(operator)。此运算符能够测试在运行时计算的值,并根据该值执行两个分支之一。
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()
。
关于python - TensorFlow 将图像张量调整为动态形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35208832/