baoshiwei
2025-04-15 776a127b8db01cd4338f4db2a84ea567a65bff9f
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import cv2
import time
import numpy as np
import onnxruntime
from scipy.special import softmax
 
# 加载ONNX模型
session = onnxruntime.InferenceSession("model/classify/s.onnx")
# 摄像头索引号,通常为0表示第一个摄像头
camera_index = 0
 
# 打开摄像头
cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
# 设置分辨率
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 3840)  # 宽度
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 2160)  # 高度
# 检查摄像头是否成功打开
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
 
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print("摄像头分辨率:", width, "x", height)
 
 
 
# 从res.json中读取类别
with open("res1-2.json", "r") as f:
    classes = eval(f.read())
 
 
 
# 目标图像尺寸
target_width = 1024
target_height = 768
 
# 计时器
start_time = time.time()
 
# 循环读取摄像头画面
while True:
    ret, frame = cap.read()
 
    if not ret:
        print("无法读取摄像头画面")
        break
 
    # 1920*1080的图像,中心裁剪640*480的区域
    cropped_frame = frame[int(height / 2 - target_height / 2):int(height / 2 + target_height / 2),
                    int(width / 2 - target_width / 2):int(width / 2 + target_width / 2)]
    # 调整图像尺寸
    resized_frame = cv2.resize(cropped_frame, (target_width, target_height))
 
    # 获取当前时间
    current_time = time.time()
 
    #如果距离上一次保存已经过去1秒,则保存当前画面
    # if current_time - start_time >= 3.0:
    #     # 生成保存文件名,以当前时间命名
    #     save_name = time.strftime("%Y%m%d%H%M%S", time.localtime()) + ".jpg"
    #     # 保存调整尺寸后的图片
    #     cv2.imwrite(save_path + save_name, frame)
    #     print("保存图片:", save_name)
    #     # 重置计时器
    #     start_time = time.time()
 
    # 预处理
    blob = cv2.dnn.blobFromImage(resized_frame, 1 / 255.0, (640, 640), swapRB=True, crop=False)
 
    # 模型推理
    outputs = session.run(None, {session.get_inputs()[0].name: blob})
 
    # print(outputs)
    # 应用softmax函数
    probabilities = outputs[0]
 
    # 找到最大概率的类别
    predicted_class = np.argmax(probabilities, axis=1)[0]
    max_probability = np.max(probabilities, axis=1)[0]
 
    # 找到概率较高的前十个类别
    top_ten_classes = np.argsort(probabilities, axis=1)[0][-5:]
 
    # 输出前十个类别
    print("Top 5 Classes:")
    for i in top_ten_classes:
        print(f"{classes[i]}: {probabilities[0][i]}")
 
    # 显示画面
    cv2.imshow("Camera", resized_frame)
 
    # 检测按键,如果按下q键则退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# 关闭摄像头
cap.release()
 
# 关闭所有窗口
cv2.destroyAllWindows()