基于Anaconda的Windows端yolov5模型部署(onnx模型部署黑色砝码识别)-树莓派5部署步骤同样适用

硬件及环境支持:

      硬件:

 

软件: Anaconda3(自行安装)

部署环境配置:

 打开文件夹后如下图:

具体了解各文件,代码等可参考以下博主的优秀博客:【Yolov5】1.认真总结6000字Yolov5保姆级教程(2022.06.28全新版本v6.1)_yolov5教程-CSDN博客 

  • 下一步就是运行此源码,这里我们利用 Anaconda3搭建环境,电脑开始菜单栏下找到Anaconda3文件夹,点击如下:

 打开后如图所示:

接下来创建环境、激活环境: 

创建环境、如下:

 conda create -n yolov5s python=3.11 

输入y确定:

 出现如下界面,环境创建完成:

 

 激活环境:

conda activate yolov5s

如下为成功激活:环境由base切换为yolov5s:

  

  •  下载安装yolov5s需要的依赖:

 cd 到下载的yolovs源码文件夹:

 完成后如下:

我们可以通过ls指令查看该目录下的内容:

通过下面标志的这个txt下载安装依赖:指令为:

pip install -r requirements.txt

运行后发现指令有错误:

 

解决方法为输入pip install -r requ后直接按Tab键补齐、如下:

pip install -r .\requirements.txt

 

安装完成后,查看依赖:

pip list

 此时可成功运行yolov5s,但是为了后续转换为onnx模型的成功部署,我们还需导入onnx、onnxruntime

pip install onnx
pip install onnxruntime

成功安装: Successfully installed onnx-1.16.1

 成功安装:Successfully installed coloredlogs-15.0.1 flatbuffers-24.3.25 humanfriendly-10.0 onnxruntime-1.18.0 pyreadline3-3.4.1

 

运行yolov5s识别程序 

默认数据集在此路径下:\yolov5-master\data\images 

 

直接对其进行识别:

python detect.py

可以看到识别结果保存在  runs\detect\exp3这个文件夹下:

 可以看到图像被成功识别:

 若想采用摄像头实时识别可以运行以下代码:

source 0;0为摄像头索引,笔记本只有一个摄像头的应该都为0,有外接摄像头的可以尝试1或者2...等。

 python .\detect.py --source 0

 识别FPS感觉略低

接下来我们尝试运行onnx模型对黑色砝码进行识别:

代码及onnx模型:

 代码引用以下博主的博客,如何修改及应用也可参考:http://t.csdnimg.cn/qxEwm

onnx 模型由export.py转换得到

import cv2
import numpy as np
import onnxruntime as ort
import time
 
def plot_one_box(x, img, color=None, label=None, line_thickness=None):
    """
    description: Plots one bounding box on image img,
                 this function comes from YoLov5 project.
    param: 
        x:      a box likes [x1,y1,x2,y2]
        img:    a opencv image object
        color:  color to draw rectangle, such as (0,255,0)
        label:  str
        line_thickness: int
    return:
        no return
    """
    tl = (
        line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1
    )  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
    if label:
        tf = max(tl - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
        cv2.putText(
            img,
            label,
            (c1[0], c1[1] - 2),
            0,
            tl / 3,
            [225, 255, 255],
            thickness=tf,
            lineType=cv2.LINE_AA,
        )
 
def _make_grid( nx, ny):
        xv, yv = np.meshgrid(np.arange(ny), np.arange(nx))
        return np.stack((xv, yv), 2).reshape((-1, 2)).astype(np.float32)
 
def cal_outputs(outs,nl,na,model_w,model_h,anchor_grid,stride):
    
    row_ind = 0
    grid = [np.zeros(1)] * nl
    for i in range(nl):
        h, w = int(model_w/ stride[i]), int(model_h / stride[i])
        length = int(na * h * w)
        if grid[i].shape[2:4] != (h, w):
            grid[i] = _make_grid(w, h)
 
        outs[row_ind:row_ind + length, 0:2] = (outs[row_ind:row_ind + length, 0:2] * 2. - 0.5 + np.tile(
            grid[i], (na, 1))) * int(stride[i])
        outs[row_ind:row_ind + length, 2:4] = (outs[row_ind:row_ind + length, 2:4] * 2) ** 2 * np.repeat(
            anchor_grid[i], h * w, axis=0)
        row_ind += length
    return outs
 
 
 
def post_process_opencv(outputs,model_h,model_w,img_h,img_w,thred_nms,thred_cond):
    conf = outputs[:,4].tolist()
    c_x = outputs[:,0]/model_w*img_w
    c_y = outputs[:,1]/model_h*img_h
    w  = outputs[:,2]/model_w*img_w
    h  = outputs[:,3]/model_h*img_h
    p_cls = outputs[:,5:]
    if len(p_cls.shape)==1:
        p_cls = np.expand_dims(p_cls,1)
    cls_id = np.argmax(p_cls,axis=1)
 
    p_x1 = np.expand_dims(c_x-w/2,-1)
    p_y1 = np.expand_dims(c_y-h/2,-1)
    p_x2 = np.expand_dims(c_x+w/2,-1)
    p_y2 = np.expand_dims(c_y+h/2,-1)
    areas = np.concatenate((p_x1,p_y1,p_x2,p_y2),axis=-1)
    
    areas = areas.tolist()
    ids = cv2.dnn.NMSBoxes(areas,conf,thred_cond,thred_nms)
    if len(ids)>0:
        return  np.array(areas)[ids],np.array(conf)[ids],cls_id[ids]
    else:
        return [],[],[]
def infer_img(img0,net,model_h,model_w,nl,na,stride,anchor_grid,thred_nms=0.4,thred_cond=0.5):
    # 图像预处理
    img = cv2.resize(img0, [model_w,model_h], interpolation=cv2.INTER_AREA)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = img.astype(np.float32) / 255.0
    blob = np.expand_dims(np.transpose(img, (2, 0, 1)), axis=0)
 
    # 模型推理
    outs = net.run(None, {net.get_inputs()[0].name: blob})[0].squeeze(axis=0)
 
    # 输出坐标矫正
    outs = cal_outputs(outs,nl,na,model_w,model_h,anchor_grid,stride)
 
    # 检测框计算
    img_h,img_w,_ = np.shape(img0)
    boxes,confs,ids = post_process_opencv(outs,model_h,model_w,img_h,img_w,thred_nms,thred_cond)
 
    return  boxes,confs,ids
 
 
 
 
if __name__ == "__main__":
 
    # 模型加载
    model_pb_path = "best.onnx"
    so = ort.SessionOptions()
    net = ort.InferenceSession(model_pb_path, so)
    
    # 标签字典
    dic_labels= {0:'weight'

          }
    
    # 模型参数
    model_h = 320
    model_w = 320
    nl = 3
    na = 3
    stride=[8.,16.,32.]
    anchors = [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]]
    anchor_grid = np.asarray(anchors, dtype=np.float32).reshape(nl, -1, 2)
    
    video = 0
    cap = cv2.VideoCapture(video)
    flag_det = False
    while True:
        success, img0 = cap.read()
        if success:
            
            if flag_det:
                t1 = time.time()
                det_boxes,scores,ids = infer_img(img0,net,model_h,model_w,nl,na,stride,anchor_grid,thred_nms=0.4,thred_cond=0.5)
                t2 = time.time()
            
                
                for box,score,id in zip(det_boxes,scores,ids):
                    label = '%s:%.2f'%(dic_labels[id],score)
            
                    plot_one_box(box.astype(np.int16), img0, color=(255,0,0), label=label, line_thickness=None)
                    
                str_FPS = "FPS: %.2f"%(1./(t2-t1))
                
                cv2.putText(img0,str_FPS,(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(0,255,0),3)
                
            
            cv2.imshow("video",img0)
        key=cv2.waitKey(1) & 0xFF    
        if key == ord('q'):
        
            break
        elif key & 0xFF == ord('s'):
            flag_det = not flag_det
            print(flag_det)
            
    cap.release() 

 运行代码:

 按键s开始识别,按键q退出

 python .\test.py

 同时部署于树莓派5等嵌入式设备也是类似的步骤,亲测有效:

最后也是成功部署完成识别,此文章为自己学习记录时撰写,后续会更新基于距池云训练砝码及树莓派5部署的应用,有需要的可以关注参考学习,有疑问欢迎联系交流QQ:3470445202,若有侵权可联系删。

  • 28
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
YOLOv5是一种轻量级目标检测算法,适用于实时目标检测应用。而树莓派是一种低成本、高度可扩展的小型计算机,因其小巧便携和低功耗等特点,被广泛应用于物联网和嵌入式系统。要在树莓派部署YOLOv5,我们可以按照以下步骤进行操作。 首先,我们需要在树莓派上安装好操作系统(通常是Raspbian或Ubuntu),并配置好网络连接和基本的环境设置。 其次,我们需要安装Python和相关依赖库,包括PyTorch、OpenCV等。可以使用PIP或Anaconda来安装这些库,确保它们适用树莓派的ARM架构。 接下来,我们可以从YOLOv5的Github仓库中获取源代码。可以通过git clone或直接下载压缩包的方式获取源代码。 获取到源代码后,我们可以进行一些必要的配置调整。例如,可以修改配置文件以调整模型的参数、检测阈值等。此外,我们还可以选择合适的预训练权重文件,或者在自己的数据集上进行训练以获得更好的检测效果。 完成配置后,我们可以使用YOLOv5提供的命令行工具进行目标检测。通过在终中运行适当的命令,我们可以输入图像或视频进行检测,并获得检测结果。可以根据需求设置不同的参数,如输入图像大小、检测阈值等。 最后,为了方便使用,我们可以将YOLOv5以服务的形式部署树莓派上。可以使用Flask等框架来搭建简单的API,让其他设备可以通过网络调用树莓派上的目标检测功能。 总结起来,部署YOLOv5树莓派上需要安装必要的软件和依赖库,配置相应的参数,使用命令行工具进行目标检测,最后将其封装为服务,以方便其他设备调用。这样就可以在树莓派上实现实时的目标检测应用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值