我将一个文件夹中的多个jpeg图像分类,但出现此错误:“ ValueError:参数必须是密集张量:形状为[2],但想要为[2,16]”。我试图一次对每个图像进行推断,但我不确定自己在哪里出错。任何帮助将不胜感激!
相关代码:
def load_graph(model_file):
graph = tf.Graph()
graph_def = tf.GraphDef()
with tf.device('/cpu:0'):
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 load_labels(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 read_tensor_from_image_file(images):
image_file_path = "./test_images/"
filenames = [os.path.join(image_file_path, filename) for
filename in os.listdir(image_file_path)]
filename_queue = tf.train.string_input_producer((filenames,
'./*.jpg'))
image_reader = tf.WholeFileReader()
_, image_file = image_reader.read(filename_queue)
image_orig = tf.image.decode_jpeg(image_file, channels = 3,
name='jpeg_reader')
image = tf.image.resize_images(image_orig, [299, 299])
image = image.set_shape([299, 299, 3])
batch_size = 1
num_preprocess_threads = 1
min_queue_examples = 50
images = tf.train.shuffle_batch([image], batch_size =
batch_size, num_threads=num_preprocess_threads,
capacity=min_queue_examples + 10 * batch_size,
min_after_dequeue=min_queue_examples)
with tf.Session() as sess:
tf.global_variables_initializer().run()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
image_tensor = sess.run([images])
print(image_tensor)
coord.request_stop()
coord.join(threads)
def main(images):
model_file = "tf_files/retrained_graph.pb"
label_file = "tf_files/retrained_labels.txt"
input_layer = "Mul"
output_layer = "final_result"
graph = load_graph(model_file)
t = read_tensor_from_image_file(images)
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);
with tf.device('/cpu:0'):
with tf.Session(graph=graph) as sess:
config = tf.ConfigProto(device_count={"CPU": 4},
inter_op_parallelism_threads=44,
intra_op_parallelism_threads=44)
sess = tf.Session(config=config)
start = time.time()
results = 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(images, labels[i], results[i])
return [images] + list(results)
if __name__ == "__main__":
image_list = [f for f in listdir('test_images') if
isfile(join('test_images', f))]
res_list = []
for image in image_list:
if image.lower().endswith(('.png', '.jpg',
'.jpeg', '.gif')):
res_list.append(main(join('test_images',
image)))
else:
if not image.endswith('.jpg') or
image.startswith('.'):
continue