欢迎访问宙启技术站
智能推送

使用ResNet_v1_101进行图像分类的Python代码示例

发布时间:2023-12-24 12:29:39

下面是一个使用ResNet_v1_101进行图像分类的示例代码:

import tensorflow as tf
from tensorflow.keras.applications import ResNet101V1
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet_v1 import preprocess_input, decode_predictions

# 加载预训练模型
model = ResNet101V1(weights='imagenet')

# 加载待分类的图像
img_path = 'example.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = preprocess_input(x)
x = tf.expand_dims(x, axis=0)

# 进行图像分类
preds = model.predict(x)
predictions = decode_predictions(preds, top=3)[0]

# 输出预测结果
for _, label, prob in predictions:
    print(f"{label}: {prob*100}%")

在这个示例代码中,我们首先导入了必要的库。接下来,我们使用ResNet101V1模型加载了预先训练的权重(weights='imagenet'表示加载ImageNet预训练的权重)。

然后,我们指定待分类的图像路径,并用image.load_img加载图像,并将其大小调整为224x224像素。然后,我们使用image.img_to_array将图像转换为numpy数组,并使用preprocess_input函数对图像进行预处理。我们还使用tf.expand_dims对输入进行扩展,以适应模型的输入要求。

接下来,我们使用模型的predict方法对图像进行分类。predict方法返回一个概率数组,表示图像属于每个类别的概率。我们使用decode_predictions函数将概率数组转换为人类可读的标签和概率。在这个示例中,我们选择了概率最高的3个预测结果进行打印。

要运行这个示例代码,你需要将example.jpg替换为你想要分类的图像路径。然后,你可以根据输出结果来查看图像的预测分类及其概率。