【v5Lite】识别+串口


前言

尝试调试【v5Lite】识别+串口功能的程序时候的记录。基本上前两个版本不用看,直接看第三个
前两个版本的帧数计算有问题哈。


一、版本一

'''

'''
#Author :susocool
#Creattime:2024/10/16
#FileName:4-线程带异常处理
#Description: 1、帧数显示、加入异常处理
              2、线程处理-推理部分放在另一个线程中
'''
import sys
sys.path.append('/home/pi/Desktop/Lite')
import torch
import cv2
import numpy as np
from models.experimental import attempt_load
from utils.general import non_max_suppression, scale_coords
from utils.plots import plot_one_box
from queue import Queue, Empty
import threading
import time
import sys 
print(sys)

# 加载模型权重,指定CPU
try:
    model = attempt_load('/home/pi/Desktop/Lite/v5lite-s.pt',
                          map_location=torch.device('cpu'))
    model.eval()
except Exception as e:
    print(f"加载模型失败: {e}")
    exit()

# 初始化摄像头
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print("无法打开摄像头")
    exit()

# 创建一个队列来存储从摄像头捕获的帧
frame_queue = Queue()
# 创建一个队列来存储推理结果
result_queue = Queue()


# 定义推理线程函数
def inference_thread(model, frame_queue, result_queue):
    while True:
        try:
            # 从队列中获取帧
            frame = frame_queue.get(timeout=1)  # 设置超时以避免阻塞
            if frame is None:  # 如果收到None,则退出线程
                break

            # 将图像转换为 YOLOv5 模型所需的格式
            global img
            img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            img = torch.from_numpy(img).permute(2, 0, 1).float().div(255.0).unsqueeze(0)

            # 进行推理
            with torch.no_grad():
                pred = model(img)[0]

            # 非极大值抑制
            pred = non_max_suppression(pred, conf_thres=0.5, iou_thres=0.5)

            # 将结果放入结果队列
            result_queue.put(pred)
        except Empty:
            # 如果队列为空,则继续下一次循环(通常不会发生,因为设置了超时)
            continue
        except Exception as e:
            print(f"推理线程出现异常: {e}")


# 启动推理线程
inference_thread_obj = threading.Thread(target=inference_thread, args=(model, frame_queue, result_queue))
inference_thread_obj.start()

# 用于计算帧率的变量
frame_count = 0
start_time = time.time()


try:
    while True:
        
        # 设置摄像头的分辨率,防止其因为分辨率不能正常显示画面
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        # 捕获摄像头的帧
        ret, frame = cap.read()
        if not ret:
            print("无法获取摄像头的的数据")
            break

        # 将帧放入队列以供推理线程处理
        try:
            frame_queue.put(frame)
        except Exception as e:
            print(f"将帧放入队列时出现异常: {e}")

        # 尝试从结果队列中获取推理结果
        try:
            pred = result_queue.get_nowait()  # 使用nowait以避免阻塞,如果没有结果则跳过绘制

            # 处理预测结果
            for det in pred:
                if det is not None and len(det):
                    det[:, :4] = scale_coords(img.shape[2:], det[:, :4], frame.shape).round()
                    for *xyxy, conf, cls in det:
                        label = f'{model.names[int(cls)]} {conf:.2f}'
                        label_onlyName = f'{model.names[int(cls)]}'
                        plot_one_box(xyxy, frame, label=label, color=(0, 255, 0), line_thickness=3)
                        print(label_onlyName
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值