網站首頁 編程語言 正文
yolov5 調用 usb 攝像頭
文章是在yolov5 v5.0版本的detect.py所修改編寫
其他v1.0-v4.0沒有試過,你們可以試試。
具體用法已經寫在代碼里面了。
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', #訓練好的模型路徑 (必改) imgsz=512, #訓練模型設置的尺寸 (必改) cap = 0, #攝像頭 conf_thres=0.25, #置信度 iou_thres=0.45, #NMS IOU 閾值 max_det=1000, #最大偵測的目標數 device='', #設備 crop=True, #顯示預測框 classes=None, #種類 agnostic_nms=False, #class-agnostic NMS augment=False, #是否擴充推理 half=False, #使用FP16半精度推理 hide_labels=False, #是否隱藏標簽 hide_conf=False, #是否隱藏置信度 line_thickness=3 #預測框的線寬 ): # #--------------------這里更改配置-------------------- #----------------------------------------------------- #打開攝像頭 cap = cv2.VideoCapture(cap) #-----初始化----- set_logging() #設置設備 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()))) # 跑一次 #-----進入循環:ESC退出----- while(True): #設置labels--記錄標簽/概率/位置 labels = [] #計時 t0 = time.time() ref,img0=cap.read() #填充調整大小 img = letterbox(img0, imgsz, stride=stride)[0] # 轉換 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() #目標進程 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() # 輸出結果 for c in det[:, -1].unique(): #每類檢測數 n = (det[:, -1] == c).sum() #添加到字符串 s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # 結果輸出 for *xyxy, conf, cls in reversed(det): #歸一化xywh xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() #標簽格式 line = (cls, *xywh, conf) #整數類 c = int(cls) #建立標簽 label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}') #繪畫預測框 if crop: plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness) #記錄標簽/概率/位置 labels.append([names[c],conf,xyxy]) #--------------------這里寫/修改代碼-------------------- #------------------------------------------------- ''' labels里面有該圖片的標簽/概率/坐標(列表) labels = [ [列表0] , [列表1] , [列表3] ,......] 其中 列表 = [標簽,概率,坐標] 例如獲取第一個預測框的概率值:print( float( labels[0][1]) ) ''' # 顯示圖片 cv2.imshow("666",im0) #輸出計算時間 print(f'消耗時間: ({time.time() - t0:.3f}s)') key = cv2.waitKey(20) #這里設置ESC退出 if key == 27: break #--------------------END-------------------- #------------------------------------------------- cv2.destroyAllWindows() if __name__ == "__main__": ''' 修改配置在 13-28 行 寫代碼-顯示輸出/獲取預測框位置/獲取預測概率值 在121-END行 ''' #檢測安裝包--建議注釋掉 #check_requirements(exclude=('tensorboard', 'thop')) #運行 detect()
經研究發現,yolov5-master有time_synchronized 和 time_sync 兩種名字,所以如果time_synchronized報錯,麻煩換成time_sync
YOLOv5調用本地攝像頭
YOLOv5源碼:https://github.com/ultralytics/yolov5
最近用YOLOv5做目標檢測,直接調用本地攝像頭會報錯,需要在dataset中做一點修改。
具體如下:
在279行的這兩處改成str類型
然后在detect里把這里的參數改為0
然后運行detect.py即可調用本地攝像頭。
總結
原文鏈接:https://blog.csdn.net/weixin_50518868/article/details/119359146
相關推薦
- 2022-02-24 React插槽使用方法_React
- 2022-06-16 c語言單詞搜索的實現_C 語言
- 2022-05-07 Python數據結構之棧詳解_python
- 2022-10-26 Pytorch中torch.stack()函數的深入解析_python
- 2023-04-20 navicat 連接 mongodb 報錯[13][Unauthorized] command li
- 2022-07-16 (ES6以上以及TS) Map對象轉數組
- 2022-08-21 Android實現手寫板功能_Android
- 2022-11-22 Nginx?Tomcat負載均衡動靜分離原理解析_nginx
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支