tf.reshape尺寸与tf.decode_raw的输出不匹配

时间:2019-11-12 09:39:28

标签: python tensorflow image-processing deep-learning

import cv2
img = cv2.imread(cat_in_snow)
height, width, channels = img.shape
print (height, width, channels)
  
    

上述代码段的输出为[213 320 3]

  
raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')
# Create a dictionary describing the features.
image_feature_description = {
    'height': tf.io.FixedLenFeature([], tf.int64),
    'width': tf.io.FixedLenFeature([], tf.int64),
    'depth': tf.io.FixedLenFeature([], tf.int64),
    'label': tf.io.FixedLenFeature([], tf.int64),
    'image_raw': tf.io.FixedLenFeature([], tf.string),
}

def _parse_image_function(example_proto):
  # Parse the input tf.Example proto using the dictionary above.
  return tf.io.parse_single_example(example_proto, image_feature_description)

parsed_image_dataset = raw_image_dataset.map(_parse_image_function)

for image_features in parsed_image_dataset:  
  print(image_features['image_raw'])
  image_raw = image_features['image_raw'].numpy()
  dec_img = tf.io.decode_raw(image_features['image_raw'], tf.uint8)
  img = tf.reshape(dec_img,[213 ,320, 3])

  
    

InvalidArgumentError:要重塑的输入是具有17858个值的张量,但请求的形状为204480 [Op:Reshape]

  

上面的文件包含与opencv read中使用的图像相同的图像,但是encode_raw函数给出的输出不同。有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。

我发现,如果将图像字符串保存到tfrecords中,则可以使用“ tf.io.decode_raw”方法。

image_data = matplotlib.image.imread(img_path)
# Convert image to string data
image_str = image_data.tostring()

但是对我来说,我以字节为单位读取和存储图像数据,所以我改用了'tf.image.decode_image'方法。

with tf.compat.v1.gfile.FastGFile(img_path, 'rb') as fid:
                    image_data = fid.read()

希望这个答案对您有帮助。