我有下面的代码片段,用torch用Lua编写,这是一种自定义的边缘检测算法:
xGrad1[{{},{},{},{1,width-1}}] = input:narrow(4,2,width-1) - input:narrow(4,1,width-1)
yGrad1[{{},{},{1,height-1},{}}] = input:narrow(3,2,height-1) - input:narrow(3,1,height-1)
xGrad2[{{},{},{},{2,width}}] = input:narrow(4,2,width-1) - input:narrow(4,1,width-1)
yGrad2[{{},{},{2,height},{}}] = input:narrow(3,2,height-1) - input:narrow(3,1,height-1)
local xGrad = (torch.abs(self.xGrad1) + torch.abs(self.xGrad2))/2
local yGrad = (torch.abs(self.yGrad1) + torch.abs(self.yGrad2))/2
output = torch.sum(xGrad,2)+torch.sum(yGrad,2)如您所见,表示图像宽度和高度的xGrad和yGrad张量的最后两个维度只被部分更新,例如,在xGrad2中,仅从列2到宽度-1。
现在,我想用Tensorflow和Python实现同样的结果。我不确定我的一般方法是否正确,但我已经将所有4级张量初始化为一个变量,并将它们预先填充为零。现在我在为这些部分的分配而挣扎。我和Variable.assign试过了,但没有运气。
目前,这是我的代码:
input = tf.image.decode_png(tf.read_file(f), 3)
input = tf.cast(input, tf.float32)
height = tf.shape(input)[0]
width = tf.shape(input)[1]
xGrad1 = tf.Variable(tf.zeros(tf.shape(input)), validate_shape=False)
yGrad1 = tf.Variable(tf.zeros(tf.shape(input)), validate_shape=False)
xGrad2 = tf.Variable(tf.zeros(tf.shape(input)), validate_shape=False)
yGrad2 = tf.Variable(tf.zeros(tf.shape(input)), validate_shape=False)
xGrad1[:, :width-2].assign(input[:,1:width-2] - input[:,:width-2])
yGrad1[:height-2].assign(input[1:height-2] - input[:height-2])
xGrad2[:, 1:width-1].assign(input[:,1:width-2] - input[:,:width-2])
yGrad2 [1, height-1].assign(input[1:height-2] - input[:height-2])
xGrad = (tf.abs(xGrad1) + tf.abs(xGrad2)) / 2
yGrad = (tf.abs(yGrad1) + tf.abs(yGrad2)) / 2
output = tf.reduce_sum(xGrad,axis=2) + tf.reduce_sum(yGrad,axis=2)在将列表索引从Lua转换到python之后,当直接输出作为4个赋值命令的参数的计算时,我得到了不错的结果,但是输出xGrad1的内容时只有一个黑色的图像。
我假设存在形状不兼容的问题,但我已经将validate_shapes切换为False,因为在会话创建时我不知道输入的形状,因为输入图像是在会话开始后加载的。如果有人对此也有想法,请回答我,但现在我只是问如何只部分分配一个变量张量。
发布于 2017-11-24 01:02:13
如果你想做一个切片作业,,你必须遵循这样的方法,
with tf.control_dependencies([xGrad1[:, :width-2].assign(input[:,1:width-2] - input[:,:width-2]), yGrad1[:height-2].assign(input[1:height-2] - input[:height-2]),xGrad2[:, 1:width-1].assign(input[:,1:width-2] - input[:,:width-2]),yGrad2 [1, height-1].assign(input[1:height-2] - input[:height-2])]): # should give the list of slice assignment here
xGrad = (tf.abs(xGrad1) + tf.abs(xGrad2)) / 2
yGrad = (tf.abs(yGrad1) + tf.abs(yGrad2)) / 2
output = tf.reduce_sum(xGrad,axis=2) + tf.reduce_sum(yGrad,axis=2)
sess = tf.Session()
with sess.as_default():
sess.run(tf.global_variables_initializer())
output= output.eval()下面是对Tensorflow,https://stackoverflow.com/a/43139565/6531137中切片赋值的一个很好的解释
希望这能有所帮助。
https://stackoverflow.com/questions/47450903
复制相似问题