TensorFlow Slim Inception ResNet V2高效单图热切换推理实现咨询
嘿,我正好有过类似的实践经验,帮你搞定这个问题!
核心思路
要实现模型仅加载一次+热切换输入,关键是把「计算图构建、模型权重加载」这两个耗时操作放在循环外面,只执行一次;然后在循环里重复做「读取图片→预处理→喂入模型推理」的流程,这样就不会每次重建图了。
之前用fifo_queue挂起的原因是:队列需要配套生产者线程持续喂数据,而你手动用feed_dict的方式没法给队列正确填充数据,导致会话一直等待队列输出,自然就挂住了。换成输入占位符会更适合这种手动逐张输入的场景。
具体实现步骤&代码示例
1. 准备工作
确保你已经有slim库的环境,以及预训练的inception_resnet_v2权重文件。
2. 构建计算图+加载模型(仅执行一次)
import tensorflow as tf from nets import inception_resnet_v2 from preprocessing import inception_preprocessing import os # 重置默认图(避免重复构建) tf.reset_default_graph() # 定义输入占位符:接受任意尺寸的RGB图片 image_size = inception_resnet_v2.inception_resnet_v2.default_image_size input_img = tf.placeholder(tf.uint8, shape=[None, None, 3]) # 预处理图片:和模型训练/评估时的逻辑完全一致 processed_img = inception_preprocessing.preprocess_image( input_img, image_size, image_size, is_training=False ) # 扩展维度为批量格式(模型要求输入是[batch_size, height, width, 3]) processed_img = tf.expand_dims(processed_img, 0) # 构建Inception Resnet V2模型 with tf.contrib.slim.arg_scope(inception_resnet_v2.inception_resnet_v2_arg_scope()): logits, _ = inception_resnet_v2.inception_resnet_v2( processed_img, num_classes=1001, is_training=False ) # 可选:生成预测类别索引 predictions = tf.argmax(logits, axis=1) # 加载预训练权重 checkpoint_path = "你的预训练权重文件路径/inception_resnet_v2.ckpt" saver = tf.train.Saver() # 启动会话并加载模型 sess = tf.Session() saver.restore(sess, checkpoint_path) print("✅ 模型加载完成!请输入图片路径(输入q退出):")
3. 循环接收命令行输入并推理
while True: img_path = input("> ") # 退出逻辑 if img_path.strip().lower() == "q": print("👋 再见!") sess.close() break # 检查图片是否存在 if not os.path.exists(img_path): print("❌ 图片不存在,请重新输入!") continue # 读取并解码图片 with tf.gfile.FastGFile(img_path, "rb") as f: img_data = f.read() decoded_img = tf.image.decode_jpeg(img_data, channels=3) # 将张量转为numpy数组(方便喂入占位符) img_np = sess.run(decoded_img) # 执行推理 pred_idx, logits_val = sess.run( [predictions, logits], feed_dict={input_img: img_np} ) # 输出结果(这里可以换成你自己的标签映射) print(f"📊 预测类别索引:{pred_idx[0]}") print(f"📈 Logits前5个值:{logits_val[0][:5]}\n")
关键注意点
- 预处理一致性:必须保证推理时的图片预处理和训练/评估时完全一致,否则模型输出会出错。这里用了
slim自带的inception_preprocessing,和模型的默认逻辑匹配。 - 批量维度:模型输入要求是批量格式,所以我们用
tf.expand_dims给单张图片加了一个批量维度,推理后再取[0]得到单张的结果。 - 会话管理:会话只创建一次,循环内复用,避免每次重建会话和图带来的开销。
内容的提问来源于stack exchange,提问作者user3180
相关产品推荐
相关产品推荐

