test.py
1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import tensorflow as tf
from tensorflow import keras
import numpy as np
# 加载预训练的模型
model = keras.applications.MobileNetV2(weights="imagenet")
# 加载图像分类标签
labels_path = tf.keras.utils.get_file(
"ImageNetLabels.txt",
"https://storage.googleapis.com/download.tensorflow.org/data/ImageNetLabels.txt",
)
with open(labels_path) as f:
labels = f.readlines()
labels = [label.strip() for label in labels]
# 加载并预处理图像
def preprocess_image(image_path):
img = keras.preprocessing.image.load_img(image_path, target_size=(224, 224))
img_array = keras.preprocessing.image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = tf.keras.applications.mobilenet_v2.preprocess_input(img_array)
return img_array
# 图像分类
def classify_image(image_path):
img_array = preprocess_image(image_path)
predictions = model.predict(img_array)
predicted_label = labels[np.argmax(predictions)]
return predicted_label
# 测试图片分类
image_path = "./55e9354cefebf6b3137a9cfa7e69b87.png" # 替换为你的图片路径
predicted_label = classify_image(image_path)
print("预测结果:", predicted_label)