Skip to main content
 首页 » 编程设计

python之提高 Tensorflow 图像分类的速度

2025年02月15日30daizhj

使用来自 Link 的说明,我已经为新类别重新训练了 tensorflow inception。

但我注意到,随后如果我想对一组图像进行分类,它会一张一张地检查图像,然后对其进行分类。如果数据集很大,需要很长时间才能完成分类。例如,1000 张图像需要 45 分钟。

对于图像分类,我使用可用的 LabelImage.py online如下:

import tensorflow as tf 
import sys 
 
image_path = sys.argv[1] #Pass the test file as argument 
 
# Read in the image_data 
image_data = tf.gfile.FastGFile(image_path, 'rb').read() 
 
# Loads label file (the retained labels from retraining) and strips off carriage return 
label_lines = [line.rstrip() for line 
                   in tf.gfile.GFile("/tf_files/tf_files/retrained_labels.txt")] 
 
# Unpersists graph from file 
with tf.gfile.FastGFile("/tf_files/tf_files/retrained_graph.pb", 'rb') as f: 
    graph_def = tf.GraphDef() 
    graph_def.ParseFromString(f.read()) 
    _ = tf.import_graph_def(graph_def, name='') 
 
with tf.Session() as sess: 
    # Feed the image_data as input to the graph and get first prediction i.e. the most likely result 
    softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') 
 
    predictions = sess.run(softmax_tensor, \ 
             {'DecodeJpeg/contents:0': image_data}) 
 
    # Sort to show labels of first prediction in order of confidence 
    top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] 
 
    for node_id in top_k: 
        human_string = label_lines[node_id] 
        score = predictions[0][node_id] 
        print('%s (score = %.5f)' % (human_string, score)) 

如您所见,它会逐张处理一张图片。

是否可以加快这个过程?当我重新训练库时,它不是为多个 GPU 编译的。有没有其他方法可以加快分类过程?

请您参考如下方法:

为了优化 androidtest 给出的答案,如果您使用上述脚本,您将花费大部分时间为每张图像重新加载模型等。

相反,您应该只加载一次模型,并在脚本中一张一张地检查图像。