将三个图像与带有索引的 Tensorflow 合并



我在使用Tensorflow时遇到问题。我有四张图像及其相应的索引。我想从他们身上制作一个图像。我尝试了循环,tf.gather,tf.assign等,但都显示错误。如果有人帮助我,将不胜感激。我用一个小例子来解释我的问题: 我们有 4 个张量及其来自张量 tf.ktop 函数的索引:(我写得像 MATLAB 只是为了简单起见(

a = [1, 2; 5, 6] a_idx = [0, 1; 2, 3] b = [3, 4; 7, 8] b_idx = [0, 1; 2, 3] c = [9, 10; 13, 14] c_idx = [0, 1; 2, 3] d = [11, 12; 15, 16] d_idx = [0, 1; 2, 3]

我正在寻找来自 a、b、c 和 d 的大图像及其索引,例如:

image = [a b; c d] image = [1, 2, 3, 4; 5, 6, 7, 8;9 10, 11, 12;13, 14, 15, 16]

在python中,我有这样的东西:

a, a_idx, b, b_idx, c, c_idx, d, d_idx
n_x = tf.Variable(tf.zeros([1, 4, 4, 1]))
n_patches = tf.extract_image_patches(
n_x,
[1, 2, 2, 1],
[1, 2, 2, 1],
[1, 1, 1, 1],
"SAME"
)

因此,n_patches是 4 个张量,我需要为每个对应于 a_idx 到 d_idx 的补丁放置 a 到 d 值。在 MATLAB 或 Numpy 中使用 for 循环对我来说真的很容易做到这一点,但在张量流中我不能

在您的评论中,我怀疑您在所需的输出中犯了一个小错误,image.

我解释你想要的被给予

values = np.array([[2, 5],
[4, 6]])
indices = np.array([[0, 3],
[2, 1]])

您的结果将是

[[2. 0. 0. 0.]
[0. 0. 0. 5.]
[0. 0. 4. 0.]
[0. 6. 0. 0.]]

因此,您希望获得一种热编码矩阵,但具有与给定索引相对应的值。这可以像这样获得:

import numpy as np
values = np.array([[2, 5],
[4, 6]])
indices = np.array([[0, 3],
[2, 1]])
# Make a matrix with only zeros
n_hots = np.zeros_like((indices))
# Now row 0,1,2 and 3 should have values corresponding to the
# indices. That is we should first "unpack" the values and indices:
indices=indices.ravel()
values=values.ravel()
# values are now: [2,5,4,6]
# indices are now: [0,3,2,1]
# values:
# n_hots[row,indices[row]]=values[indices[row]]
# e.g.
# n_hots[0,0]=2
# n_hots[1,3]=5
# n_hots[2,2]=4
# n_hots[3,1]=6
# Notice how the first slices are a ascending range of values:
# [0,1,2,3], and the second slice are the raveled indices, and the
# right hand side of the equal sign are the ravele values!
# That means we can just do the following:
n_hots[np.arange(4),indices]=values
print(n_hots)

在张量流中,它会有点不同。首先生成一个在第二轴值处具有 1 的one_hot张量:在索引处,然后将其乘以相应的索引:

import numpy as np
import tensorflow as tf
indices=tf.placeholder(shape=(None),dtype=tf.int32)
values=tf.placeholder(shape=(None),dtype=tf.float32)
one_hots=tf.one_hot(indices, tf.shape(indices)[0])
n_hots=one_hots*tf.gather(values, indices)
with tf.Session() as sess:
_values = np.array([[2, 5],
[4, 6]])
_indices = np.array([[0, 3],
[2, 1]])
n_h=sess.run(n_hots, {indices: _indices.ravel(), values:_values.ravel()})
print(n_h)

最新更新