tensorflow 图像识别代码
时间: 2023-09-03 19:12:21 浏览: 87
视频及图像tensorflow识别代码
下面是一个基于 TensorFlow 的图像识别代码示例,使用了预训练模型 Inception V3:
```python
import tensorflow as tf
import numpy as np
import os
import re
import sys
from PIL import Image
# 加载预训练模型 Inception V3
model_path = './inception_v3_graph_def.pb'
with tf.gfile.FastGFile(model_path, 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
# 定义标签列表
label_path = './imagenet_slim_labels.txt'
labels = []
with open(label_path, 'r') as f:
for line in f:
labels.append(line.rstrip())
# 读取图片并进行预处理
image_path = './images/test.jpg'
img = Image.open(image_path)
if img.mode != 'RGB':
img = img.convert('RGB')
img = img.resize((299, 299))
img = np.array(img)
img = (img - 128.0) / 128.0
# 进行图像识别
with tf.Session() as sess:
input_tensor = sess.graph.get_tensor_by_name('input:0')
output_tensor = sess.graph.get_tensor_by_name('InceptionV3/Predictions/Reshape_1:0')
predictions = sess.run(output_tensor, {input_tensor: [img]})
top_k = predictions[0].argsort()[-5:][::-1]
for i in top_k:
print(labels[i], predictions[0][i])
```
其中,`inception_v3_graph_def.pb` 和 `imagenet_slim_labels.txt` 分别是 Inception V3 模型的二进制文件和标签文件,可以从 TensorFlow 官网下载。`test.jpg` 是待识别的图片。该代码通过加载预训练模型 Inception V3 对图片进行识别,并输出前 5 个最有可能的标签及其对应的概率。
阅读全文