【问题标题】:How to extract vector of exact coordinates of the image in tensorflow?如何在张量流中提取图像精确坐标的向量?
【发布时间】:2019-04-29 18:25:16
【问题描述】:

我正在尝试使用带有 tensorflow 后端的 keras 编写 GAN 生成器模型的代码。我希望生成器输出是精确坐标中图像值的向量(对于批次中的每个图像大小相同)。这些坐标也作为生成器的输入给出。

我尝试使用 tf.gather_nd 作为函数来执行类似 numpy 的操作,从精确坐标中提取值。

img 是由 shape=(?,28,28,1) 的噪声图像生成的,

coordinates 是形状为 (?,80,2) 的输入张量,从生成的图像img 中提取 80 个点,

vect是一个输出向量,应该是(?, 80)的大小, 在哪里 ?是批量大小。

vect = Lambda(lambda x: tf.gather_nd(x, tf.cast(coordinates, 'int64')))(img)

最后这个函数的输出形状是 (?,80,28,1) 而不是 (?,80)。

如何更好地提取这些点?

【问题讨论】:

  • 所以从这个输出向量,大小为(?, 80),你想制作一个图像,将这80个值放在coordinates给出的坐标中,对吧?我认为你需要tf.scatter_nd。输出图像的形状是什么,是不是也是(?, 28, 28, 1)?没有值的图像点应该为零吗?
  • 不,我只想从图像中提取精确坐标中的值。所以输出只是一个大小为(?,80)的向量,其中?是一个批量大小
  • 嗯,好吧,所以你想获得(?,80) 向量,抱歉,我以为你输入的是这个。你说得对,你需要tf.gather_nd,我会修正我的答案。
  • 更新了我的答案,希望现在真正解决您的问题。

标签: python tensorflow keras


【解决方案1】:

您可以像这样使用tf.gather_nd 做到这一点:

import tensorflow as tf

def extract_pixels(img, coords):
    # Number of images and pixels
    s = tf.shape(coords, out_type=coords.dtype)
    n = s[0]
    p = s[1]
    # Make gather index
    i = tf.range(n)
    ii = tf.tile(i[:, tf.newaxis, tf.newaxis], [1, p, 1])
    idx = tf.concat([ii, coords], axis=-1)
    # Gather pixel values
    pixels = tf.gather_nd(tf.squeeze(img, axis=-1), idx)
    return pixels

# ...
vect = Lambda(lambda x: extract_pixels(x, tf.cast(coordinates, 'int64')))(img)

【讨论】:

  • 感谢您的回答!在一个玩具示例中这是可行的,但是当我尝试在模型中编译它时,函数tf.tile:TypeError: List of Tensors when single Tensor expected 中出现错误。我认为问题可能出在变量 p 中,因为这是一个长度为 ().. 的张量
  • @Alexandra 哪个张量的形状为()?也许您可以通过print(img)print(coords) 在错误触发之前查看张量的形状?
  • np 变量具有这些形状。 s 的形状是(3,)。如果我打印coords.get_shape(),它的值为(?, 80, 2),对于图像(?, 28,28,1)
猜你喜欢
  • 2017-05-11
  • 1970-01-01
  • 2019-06-29
  • 1970-01-01
  • 2017-10-24
  • 2010-11-28
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
相关资源
最近更新 更多