TF:从读取的二进制数据创建掩码(项目分配)

TF: Create mask from binary data read (item assignment)

问题

我正在从二进制数据库中读取数据,该数据的一部分是图像遮罩内的坐标 (x,y) 和图像本身。当我知道图像形状和坐标时,蒙版本身很容易创建。基本上我只需要创建一个空蒙版,其形状由读取的图像定义,并将像素设置为给定坐标处的一个。所以我基本上想要的是如下内容:

import tensorflow as tf
import numpy as np

# coord read from binary file
x = tf.constant([1])
y = tf.constant([1])

# shape is taken from another image read from binary file
shape = tf.shape(tf.constant(np.ones([3, 3]).astype('float32')))

# create empty image but set (x,y) = 1
mask = tf.zeros(shape)
mask[x, y] = 1

由于类型错误而失败:

TypeError: 'Tensor' object does not support item assignment

尝试 1

tmp = np.zeros([3, 3])
tmp[x, y] = 1
mask = tf.constant([tmp.tolist()])

首先我认为创建一个包含所需数据的 numpy 数组然后使用 tf.constant() 将其转换为张量可能是一个好方法。但这会导致问题,我不能使用 Tensors x, y 进行索引。这是因为在创建时,这些只是要从数据库中读取的数据的占位符(当我想从二进制数据中读取 3x3 大小时,同样的问题也会出现)。请注意,运行在会话中使用张量 x 和 y 来获取值对我来说不是解决方案,因为我需要数据来训练网络。因此有必要在 运行.

的一次调用中获取和处理所有数据

尝试 2

zero_tensor = tf.zeros(shape)
delta = tf.SparseTensor([[1, 1]], [1.0], [3, 3])
mask = zero_tensor + tf.sparse_tensor_to_dense(delta)

sess = tf.Session()
mask_val = sess.run([mask])
print mask_val

在网上我找到了如何创建稀疏张量并使用它来修改张量的解决方案。问题是,掩码的坐标和形状需要硬编码,不能在 运行 时间从张量读取中获取。

感谢您的建议。

您的 尝试 2 就快到了!

函数 tf.SparseTensor() 或更好的函数 tf.sparse_to_dense(sparse_indices, output_shape, sparse_values)(参见 doc.)允许您将读取的数据作为 sparse_indicesoutput_shape .


代码如下:

import tensorflow as tf
import numpy as np

# coord read from binary file
x = tf.constant([1])
y = tf.constant([1])

# shape is taken from another image read from binary file
shape = tf.constant([3, 3])

# Little modification to get the right shape for the indices
sparse_indices = tf.transpose(tf.pack([x, y]))
mask = tf.sparse_to_dense(sparse_indices, shape, 1.)