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

  • 运行效果:

  • 翻译一下

相关推荐
skywalk81631 天前
老显卡老cpu用vllm推理大模型失败Intel(R) Xeon(R) CPU E5-2643 v2
人工智能·pytorch·python·vllm
程序员爱钓鱼1 天前
Python编程实战:文件读写(文本/二进制)详解与实战
后端·python·ipython
百锦再1 天前
第6章 结构体与方法
android·java·c++·python·rust·go
TheInk1 天前
python学习笔记之Python基础教程(crossin全60课)
笔记·python·学习
尘缘浮梦1 天前
RobotFramework框架环境搭建
linux·开发语言·python
程序员爱钓鱼1 天前
Python编程实战:try...except...finally —— 让程序更稳健的异常处理机制
后端·python
岁岁岁平安1 天前
python MongoDB 基础
数据库·python·mongodb
闲人编程1 天前
用Python控制硬件:Raspberry Pi项目初体验
开发语言·python·raspberry·pi·codecapsule·控制硬件
寻星探路1 天前
测试开发话题10---自动化测试常用函数(2)
java·前端·python
鸢尾掠地平1 天前
Python中常用内置函数上【含代码理解】
开发语言·python