yolov5調(diào)用usb攝像頭及本地攝像頭的方法實例
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, #最大偵測的目標(biāo)數(shù) device='', #設(shè)備 crop=True, #顯示預(yù)測框 classes=None, #種類 agnostic_nms=False, #class-agnostic NMS augment=False, #是否擴充推理 half=False, #使用FP16半精度推理 hide_labels=False, #是否隱藏標(biāo)簽 hide_conf=False, #是否隱藏置信度 line_thickness=3 #預(yù)測框的線寬 ): # #--------------------這里更改配置-------------------- #----------------------------------------------------- #打開攝像頭 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() #------運行推理------ if device.type != 'cpu': model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # 跑一次 #-----進入循環(huán):ESC退出----- while(True): #設(shè)置labels--記錄標(biāo)簽/概率/位置 labels = [] #計時 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)進程 for i, det in enumerate(pred): # 每幅圖像的檢測率 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(): #每類檢測數(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ù)測框 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)] 例如獲取第一個預(yù)測框的概率值:print( float( labels[0][1]) ) ''' # 顯示圖片 cv2.imshow("666",im0) #輸出計算時間 print(f'消耗時間: ({time.time() - t0:.3f}s)') key = cv2.waitKey(20) #這里設(shè)置ESC退出 if key == 27: break #--------------------END-------------------- #------------------------------------------------- cv2.destroyAllWindows() if __name__ == "__main__": ''' 修改配置在 13-28 行 寫代碼-顯示輸出/獲取預(yù)測框位置/獲取預(yù)測概率值 在121-END行 ''' #檢測安裝包--建議注釋掉 #check_requirements(exclude=('tensorboard', 'thop')) #運行 detect()
經(jīng)研究發(fā)現(xiàn),yolov5-master有time_synchronized 和 time_sync 兩種名字,所以如果time_synchronized報錯,麻煩換成time_sync
YOLOv5調(diào)用本地攝像頭
YOLOv5源碼:https://github.com/ultralytics/yolov5
最近用YOLOv5做目標(biāo)檢測,直接調(diào)用本地攝像頭會報錯,需要在dataset中做一點修改。
具體如下:
在279行的這兩處改成str類型
然后在detect里把這里的參數(shù)改為0
然后運行detect.py即可調(diào)用本地攝像頭。
總結(jié)
到此這篇關(guān)于yolov5調(diào)用usb攝像頭及本地攝像頭的文章就介紹到這了,更多相關(guān)yolov5調(diào)用攝像頭內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?PyJWT庫簡化JSON?Web?Token的生成與驗證
PyJWT庫為Python開發(fā)者提供了簡便的生成和驗證JWT的工具,本文將深入介紹PyJWT庫的核心概念、功能以及實際應(yīng)用,通過豐富的示例代碼,幫助大家更全面地了解和應(yīng)用這一強大的JWT庫2023-12-12python使用urllib2模塊獲取gravatar頭像實例
python使用urllib2模塊獲取gravatar頭像的實例,大家參考使用吧2013-12-12python開發(fā)之字符串string操作方法實例詳解
這篇文章主要介紹了python開發(fā)之字符串string操作方法,以實例形式較為詳細(xì)的分析了Python針對字符串的轉(zhuǎn)義、連接、換行、輸出等操作技巧,需要的朋友可以參考下2015-11-11安裝Python和pygame及相應(yīng)的環(huán)境變量配置(圖文教程)
下面小編就為大家?guī)硪黄惭bPython和pygame及相應(yīng)的環(huán)境變量配置(圖文教程)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06python使用opencv resize圖像不進行插值的操作
這篇文章主要介紹了python使用opencv resize圖像不進行插值的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07解決更新tensorflow后應(yīng)用tensorboard報錯的問題
這篇文章主要介紹了解決更新tensorflow后應(yīng)用tensorboard報錯的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03python pandas庫中DataFrame對行和列的操作實例講解
今天小編就為大家分享一篇python pandas庫中DataFrame對行和列的操作實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06基于python實現(xiàn)地址和經(jīng)緯度轉(zhuǎn)換
這篇文章主要介紹了基于python實現(xiàn)地址和經(jīng)緯度轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05