【Python】OpenCV-使用ResNet50进行图像分类

使用ResNet50进行图像分类

如何使用ResNet50模型对图像进行分类。

python 复制代码
import os
import cv2
import numpy as np
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image

# 设置代理
os.environ["HTTP_PROXY"] = "http://127.0.0.1:1080"
os.environ["HTTPS_PROXY"] = "http://127.0.0.1:1080"

# 加载ResNet50模型
model = ResNet50(weights='imagenet')

# 读取和预处理图像
def preprocess_image(img_path):
    # 加载图像并调整大小为(224, 224)
    img = image.load_img(img_path, target_size=(224, 224))
    
    # 将图像转换为numpy数组
    img_array = image.img_to_array(img)
    
    # 在第0轴上添加维度,将其变为(1, 224, 224, 3)
    img_array = np.expand_dims(img_array, axis=0)
    
    # 对图像进行预处理,以适应ResNet50模型的输入要求
    img_array = preprocess_input(img_array)
    
    return img_array

# 加载图像
img_path = 'pandas.jpg'
img = preprocess_image(img_path)

# 进行预测
predictions = model.predict(img)

# 解码预测结果,获取前三个预测结果
decoded_predictions = decode_predictions(predictions, top=3)[0]

# 打印结果
print("Predictions:")
for i, (imagenet_id, label, score) in enumerate(decoded_predictions):
    print(f"{i + 1}: {label} ({score:.2f})")

# 显示图像
img = cv2.imread(img_path)
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
  • 测试图片:

  • 运行效果:

  • 翻译一下

相关推荐
Zzzz_my1 小时前
正则表达式(RE)
pytorch·python·正则表达式
天天鸭1 小时前
前端仔写了个 AI Agent,才发现大模型只干了 10% 的活
前端·python·ai编程
setmoon2142 小时前
使用Scikit-learn构建你的第一个机器学习模型
jvm·数据库·python
2401_833197732 小时前
为你的Python脚本添加图形界面(GUI)
jvm·数据库·python
敏编程3 小时前
一天一个Python库:tomlkit - 轻松解析和操作TOML配置
python
2401_879693873 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
yunyun321233 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
团子和二花4 小时前
openclaw平替之nanobot源码解析(七):Gateway与多渠道集成
python·gateway·agent·智能体·openclaw·nanobot
未知鱼4 小时前
Python安全开发之简易目录扫描器(含详细注释)
开发语言·python·安全
Be1k04 小时前
推荐一款语雀知识库批量导出工具
python·gui·工具·语雀·批量导出·原创