'Tensor' object does not support item assignment

本代码中对需要对图像tensor 每一个通道进行减均值

若图像image为[BatchSize, height, width, channel],对每一个channel求图像的均值,3通道得到的均值为imgMean = [mean0, mean1, mean2]

在tensorflow中读取tfrecord数据,读到的图像为tensor,对其所有通道减去同一均值为

Image = tf.cast(Image, tf.float32) - mean 

但对三通道各减去其对应通道的均值时,若写成:

Image[:,:,0]= Image[:,:,0] - imgMean[0]
Image[:,:,1]= Image[:,:,1] - imgMean[1]
Image[:,:,2]= Image[:,:,2] - imgMean[2]

上述方式对numpy array 表达是可行的,但对tensor进行此操作,会出现'Tensor' object does not support item assignment 的错误。对tensor中某些元素赋值存在问题,对tensor整体赋值可行。

解决办法:采用中间变量,不指定tensor的具体维度即可赋值,再将中间变量赋给目标值

tmp_0 = Image[:,:,0] - imgMean[0]
tmp_1 = Image[:,:,1] -imgMean[1]
tmp_2 = Image[:,:,2] -imgMean[2]    
Image = tf.stack([tmp_0,tmp_1,tmp_2],2)


猜你喜欢

转载自blog.csdn.net/ghy_111/article/details/80839666