欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

yolov5調(diào)用usb攝像頭及本地?cái)z像頭的方法實(shí)例

 更新時(shí)間:2022年03月17日 10:27:06   作者:weixin_50518868  
YOLOV5模型從發(fā)布到現(xiàn)在都是炙手可熱的目標(biāo)檢測(cè)模型,被廣泛運(yùn)用于各大場(chǎng)景之中,下面這篇文章主要給大家介紹了關(guān)于yolov5調(diào)用usb攝像頭及本地?cái)z像頭的相關(guān)資料,需要的朋友可以參考下

yolov5 調(diào)用 usb 攝像頭

文章是在yolov5 v5.0版本的detect.py所修改編寫

其他v1.0-v4.0沒有試過,你們可以試試。

具體用法已經(jīng)寫在代碼里面了。

import time
import cv2
import numpy as np
import torch
from models.experimental import attempt_load
from utils.datasets import letterbox
from utils.general import check_img_size, non_max_suppression,scale_coords, xyxy2xywh,set_logging,check_requirements
from utils.plots import colors, plot_one_box
from utils.torch_utils import select_device,time_synchronized
 
@torch.no_grad()
def detect(
        #--------------------這里更改配置--------------------
        #---------------------------------------------------
           weights='runs/train/exp25/weights/best.pt',   #訓(xùn)練好的模型路徑   (必改)
           imgsz=512,           #訓(xùn)練模型設(shè)置的尺寸 (必改)
           cap = 0,             #攝像頭
           conf_thres=0.25,     #置信度
           iou_thres=0.45,      #NMS IOU 閾值
           max_det=1000,        #最大偵測(cè)的目標(biāo)數(shù)
           device='',           #設(shè)備
           crop=True,           #顯示預(yù)測(cè)框
           classes=None,        #種類
           agnostic_nms=False,  #class-agnostic NMS
           augment=False,       #是否擴(kuò)充推理
           half=False,          #使用FP16半精度推理
           hide_labels=False,   #是否隱藏標(biāo)簽
           hide_conf=False,     #是否隱藏置信度
           line_thickness=3     #預(yù)測(cè)框的線寬
           ):
        # #--------------------這里更改配置--------------------
        #-----------------------------------------------------
    #打開攝像頭
    cap = cv2.VideoCapture(cap)
 
    #-----初始化-----
    set_logging()
    #設(shè)置設(shè)備
    device = select_device(device)
    #CUDA僅支持半精度
    half &= device.type != 'cpu'  
 
    #-----加載模型-----
    #加載FP32模型
    model = attempt_load(weights, map_location=device)  
    #模型步幅
    stride = int(model.stride.max())  
    #檢查圖像大小
    imgsz = check_img_size(imgsz, s=stride)  
    #獲取類名
    names = model.module.names if hasattr(model, 'module') else model.names  
    #toFP16
    if half:
        model.half()  
 
    #------運(yùn)行推理------
    if device.type != 'cpu':
        model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters())))  # 跑一次
    
    #-----進(jìn)入循環(huán):ESC退出-----
    while(True):
        #設(shè)置labels--記錄標(biāo)簽/概率/位置
        labels = []
        #計(jì)時(shí)
        t0 = time.time()
        ref,img0=cap.read()
        #填充調(diào)整大小
        img = letterbox(img0, imgsz, stride=stride)[0] 
        # 轉(zhuǎn)換
        img = img[:, :, ::-1].transpose(2, 0, 1)  #BGR to RGB, to 3x416x416
        img = np.ascontiguousarray(img)
 
        img = torch.from_numpy(img).to(device)
        #uint8 to fp16/32
        img = img.half() if half else img.float()  
        #0 - 255 to 0.0 - 1.0
        img /= 255.0  
        if img.ndimension() == 3:
            img = img.unsqueeze(0)
 
        # 推斷
        t1 = time_synchronized()
        pred = model(img, augment=augment)[0]
 
        # 添加 NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        t2 = time_synchronized()
 
        #目標(biāo)進(jìn)程
        for i, det in enumerate(pred):  # 每幅圖像的檢測(cè)率
            s, im0 = '', img0.copy()
            #輸出字符串
            s += '%gx%g ' % img.shape[2:]  
            #歸一化增益
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  
            if len(det):
                # 將框從img_大小重新縮放為im0大小
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
                # 輸出結(jié)果
                for c in det[:, -1].unique():
                    #每類檢測(cè)數(shù)
                    n = (det[:, -1] == c).sum()
                    #添加到字符串  
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  
                # 結(jié)果輸出
                for *xyxy, conf, cls in reversed(det):
                    #歸一化xywh
                    xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  
                    #標(biāo)簽格式
                    line = (cls, *xywh, conf)  
                    #整數(shù)類
                    c = int(cls)  
                    #建立標(biāo)簽
                    label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                    #繪畫預(yù)測(cè)框
                    if crop:    
                        plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness)
                    #記錄標(biāo)簽/概率/位置
                    labels.append([names[c],conf,xyxy])
 
        #--------------------這里寫/修改代碼--------------------
        #-------------------------------------------------
        '''
        labels里面有該圖片的標(biāo)簽/概率/坐標(biāo)(列表)
        labels = [ [列表0] , [列表1] , [列表3] ,......]
            其中 列表 = [標(biāo)簽,概率,坐標(biāo)]
        例如獲取第一個(gè)預(yù)測(cè)框的概率值:print( float( labels[0][1])  )
        '''
        # 顯示圖片
        cv2.imshow("666",im0)
        #輸出計(jì)算時(shí)間
        print(f'消耗時(shí)間: ({time.time() - t0:.3f}s)')
 
 
        key = cv2.waitKey(20)  
 
        #這里設(shè)置ESC退出
        if key == 27:
            break
        #--------------------END--------------------
        #-------------------------------------------------
    cv2.destroyAllWindows()
 
if __name__ == "__main__":
    '''
    修改配置在 13-28 行
    寫代碼-顯示輸出/獲取預(yù)測(cè)框位置/獲取預(yù)測(cè)概率值 在121-END行
    '''
    #檢測(cè)安裝包--建議注釋掉
    #check_requirements(exclude=('tensorboard', 'thop'))
    #運(yùn)行
    detect()

經(jīng)研究發(fā)現(xiàn),yolov5-master有time_synchronized 和 time_sync 兩種名字,所以如果time_synchronized報(bào)錯(cuò),麻煩換成time_sync

YOLOv5調(diào)用本地?cái)z像頭

YOLOv5源碼:https://github.com/ultralytics/yolov5

最近用YOLOv5做目標(biāo)檢測(cè),直接調(diào)用本地?cái)z像頭會(huì)報(bào)錯(cuò),需要在dataset中做一點(diǎn)修改。

具體如下:

在279行的這兩處改成str類型

然后在detect里把這里的參數(shù)改為0

然后運(yùn)行detect.py即可調(diào)用本地?cái)z像頭。

總結(jié)

到此這篇關(guān)于yolov5調(diào)用usb攝像頭及本地?cái)z像頭的文章就介紹到這了,更多相關(guān)yolov5調(diào)用攝像頭內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論