形状必须为0级,但对于输入格式为[0]的'file_reader'(op:'ReadFile'),其级别为1. [英] Shape must be rank 0 but is rank 1 for 'file_reader' (op: 'ReadFile') with input shapes: [0]

查看:54
本文介绍了形状必须为0级,但对于输入格式为[0]的'file_reader'(op:'ReadFile'),其级别为1.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试运行下面的代码,并向我抛出此错误:形状必须为0,但输入形状为[0]的'file_reader'(op:'ReadFile')的排名为1".我试图从我的目录中读取jpeg格式的图像列表,然后将它们一个接一个地分类.任何帮助将不胜感激!

Im trying to run the code below and its throwing me this error: " Shape must be rank 0 but is rank 1 for 'file_reader' (op: 'ReadFile') with input shapes: [0]". Im trying to read a list of images from my directory which are in jpeg format and then classify them one after another. Any help would be greatly appreciated!

代码:

class image_recognition_algorithm():

def __init__(self, file_name, model_file, label_file):
    self.model_file = model_file
    self.label_file = label_file
    self.file_name = file_name

def load_graph(self):
    graph = tf.Graph()
    graph_def = tf.GraphDef()

    with open(model_file, "rb") as f:
        graph_def.ParseFromString(f.read())
    with graph.as_default():
        tf.import_graph_def(graph_def)

    return graph

def read_tensor_from_image_file(self, file_name, input_height=299, input_width=299,
                input_mean=128, input_std=128):
    input_name = "file_reader"
    output_name = "normalized"
    file_reader = tf.read_file(file_name, input_name)
    image_reader = tf.image.decode_jpeg(file_reader, channels = 3, name='jpeg_reader')
    float_caster = tf.cast(image_reader, tf.float32)
    dims_expander = tf.expand_dims(float_caster, 0);
    resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])
    normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
    sess = tf.Session()
    result = sess.run(normalized)

    return result

def load_labels(self, label_file):
    label = []
    proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()
    for l in proto_as_ascii_lines:
        label.append(l.rstrip())
    return label

def main(self, file_name):
    self.model_file = "tf_files/retrained_graph.pb"
    self.label_file = "tf_files/retrained_labels.txt"
    self.input_height = 299
    self.input_width = 299
    self.input_mean = 128
    self.input_std = 128
    input_layer = "Mul"
    output_layer = "final_result"

    graph = self.load_graph()
    t = self.read_tensor_from_image_file(file_name,
                                         input_height = self.input_height,
                                         input_width = self.input_width,
                                         input_mean = self.input_mean,
                                         input_std = self.input_std)


    input_name = "import/" + input_layer
    output_name = "import/" + output_layer
    input_operation = graph.get_operation_by_name(input_name);
    output_operation = graph.get_operation_by_name(output_name);
    config = tf.ConfigProto(device_count={"CPU": 4},
                            inter_op_parallelism_threads=1,
                            intra_op_parallelism_threads=4)
    self.sess = tf.Session(graph=graph, config=config)
    start = time.time()
    results = self.sess.run(output_operation.outputs[0],
                      {input_operation.outputs[0]: t})
    end=time.time()
    results = np.squeeze(results)

    top_k = results.argsort()[-5:][::-1]
    labels = load_labels(label_file)

    print('\nEvaluation time (1-image): {:.3f}s\n'.format(end-start))

    for i in top_k:
        print(file_name, labels[i], results[i])

if __name__ == '__main__':
            model_file = "tf_files/retrained_graph.pb"
            label_file = "tf_files/retrained_labels.txt"
            list_of_imgs = []
            img_dir = "./test_images/"
            for img in os.listdir("."):
                       img = os.path.join(img_dir, img)
                       a = cv2.imread(img)
                       if img.lower().endswith(".jpg"):
                           list_of_imgs.append(a.flatten())
            file_name = np.array(list_of_imgs)
            image_recognition_algorithm_obj = 
            image_recognition_algorithm(model_file, label_file, file_name)
            image_recognition_algorithm_obj.main(file_name)

推荐答案

由于将numpy数组提供给 tf.read_file 函数,因此出现此错误.

You are getting this error because you are feeding a numpy array to tf.read_file function.

您需要为每个图像名称调用 tf.read_file 作为字符串.
正如它在 doc 中对 tf.read_file 所说的那样>,输入 filename:类型为字符串的Tensor.

You need to call tf.read_file for each image name as a string.
As it says in the doc for tf.read_file, the input filename: A Tensor of type string.

样品用量:

file_reader = tf.read_file("test.jpeg","file_reader")

这篇关于形状必须为0级,但对于输入格式为[0]的'file_reader'(op:'ReadFile'),其级别为1.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆