python-2.7 – 如何使用张量流实时对图像进行分类?

python-2.7 – 如何使用张量流实时对图像进行分类?,第1张

概述我正在尝试使用覆盆子pi相机捕捉图像并将图像实时分为三类.我所做的是使用下面的代码.它可以在第一次迭代中预测.问题是它显示我在第二次迭代后耗尽了内存.有没有什么办法解决这一问题? import numpy as npimport tensorflow as tfimport argparseimport osimport sysdef create_graph(model_file): 我正在尝试使用覆盆子pi相机捕捉图像并将图像实时分为三类.我所做的是使用下面的代码.它可以在第一次迭代中预测.问题是它显示我在第二次迭代后耗尽了内存.有没有什么办法解决这一问题?

import numpy as npimport tensorflow as tfimport argparseimport osimport sysdef create_graph(model_file):    """Creates a graph from saved GraphDef file and returns a saver."""    # Creates graph from saved graph_def.pb.    with tf.gfile.FastGfile(model_file,'rb') as f:        graph_def = tf.GraphDef()        graph_def.ParseFromString(f.read())        _ = tf.import_graph_def(graph_def,name='')def run_inference(images,out_file,labels,model_file,k=5):    # Creates graph from saved GraphDef.    create_graph(model_file)    if out_file:        out_file = open(out_file,'wb',1)    with tf.Session() as sess:        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')        for img in images:            if not tf.gfile.Exists(img):                tf.logging.fatal('file does not exist %s',img)                continue            image_data = tf.gfile.FastGfile(img,'rb').read()            predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0': image_data})            predictions = np.squeeze(predictions)            top_k = predictions.argsort()[-k:][::-1]  # Getting top k predictions            vals = []            for node_ID in top_k:                human_string = labels[node_ID]                score = predictions[node_ID]                vals.append('%s=%.5f' % (human_string,score))           rec = "%s\t %s" % (img,",".join(vals))            if out_file:                out_file.write(rec)                out_file.write("\n")            else:                print(rec)        if out_file:        print("Output stored to a file")        out_file.close()if __name__ == '__main__':    parser = argparse.ArgumentParser(description='Classify Image(s)')    parser.add_argument('-i','--in',help='input Image file ')    parser.add_argument('-li','--List',help='List file having input image paths')    parser.add_argument('-o','--out',help='Output file for storing the content')    parser.add_argument('-m','--model',help='model file path (protobuf)',required=True)    parser.add_argument('-l','--labels',help='labels text file',required=True)   parser.add_argument('-r','--root',help='path to root directory of input data')    args = vars(parser.parse_args())    # Read input    if not args['in'] and not args['List']:        print("Either -in or -List option is required.")        sys.exit(1)    if args['in']:        images = [args['in']]    else:  # List must be given        with open(args['List']) as ff:            images = filter(lambda x: x,map(lambda y: y.strip(),ff.readlines()))    # if a separate root directory given then make a new path    if args['root']:        print("input data from  : %s" % args['root'])        images = map(lambda p: os.path.join(args['root'],p),images)    with open(args['labels'],'rb') as f:        labels = [str(w).replace("\n","") for w in f.readlines()]    while True:        imagename='/home/pi/Desktop/camerasnap.jpg'        images=raspi.capture(imagename)        run_inference(images=images,out_file=args['out'],labels=labels,model_file=args['model'])
解决方法 问题是您在每个run_inference方法调用中创建图形:

while True:        imagename='/home/pi/Desktop/camerasnap.jpg'        images=raspi.capture(imagename)        run_inference(images=images,model_file=args['model'])def run_inference(images,k=5):    # Creates graph from saved GraphDef.    create_graph(model_file)    ...

由于图形可能使用GPU中的几乎所有内存,因此当代码尝试创建新图形时,它会在第二次迭代中失败.您应该只为所有程序生命创建一个图表.

试试这个:

create_graph(model_file)while True:        imagename='/home/pi/Desktop/camerasnap.jpg'        images=raspi.capture(imagename)        run_inference(images=images,model_file=args['model'])
总结

以上是内存溢出为你收集整理的python-2.7 – 如何使用张量流实时对图像进行分类?全部内容,希望文章能够帮你解决python-2.7 – 如何使用张量流实时对图像进行分类?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1193682.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存