【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()
  • 测试图片:

  • 运行效果:

  • 翻译一下

相关推荐
吃茄子的猫5 小时前
quecpython中&的具体含义和使用场景
开发语言·python
じ☆冷颜〃6 小时前
黎曼几何驱动的算法与系统设计:理论、实践与跨领域应用
笔记·python·深度学习·网络协议·算法·机器学习
数据大魔方6 小时前
【期货量化实战】日内动量策略:顺势而为的短线交易法(Python源码)
开发语言·数据库·python·mysql·算法·github·程序员创富
APIshop6 小时前
Python 爬虫获取 item_get_web —— 淘宝商品 SKU、详情图、券后价全流程解析
前端·爬虫·python
风送雨6 小时前
FastMCP 2.0 服务端开发教学文档(下)
服务器·前端·网络·人工智能·python·ai
效率客栈老秦6 小时前
Python Trae提示词开发实战(8):数据采集与清洗一体化方案让效率提升10倍
人工智能·python·ai·提示词·trae
哈里谢顿6 小时前
一条 Python 语句在 C 扩展里到底怎么跑
python
znhy_236 小时前
day46打卡
python
Edward.W7 小时前
Python uv:新一代Python包管理工具,彻底改变开发体验
开发语言·python·uv
小熊officer7 小时前
Python字符串
开发语言·数据库·python