yolov5笔记(3)——移动端部署自己的模型(随5.0更新)
一直以來學習目標檢測的最終目標就是為了移動端的部署,比方說樹莓派、jetson、安卓、ios等。之前因為實在對object_detection訓練出來的東西效果不滿意,所以當時沒繼續研究移動端部署。如今的yolov5s是給了我極大的動力,經過這幾天的研究,發現移動端的部署有這么幾條路:
(以yolov5s.pt模型為例)
目前yolov5的部署可以說是把onnx文件/torchscript文件作為中間模型去轉換到相應的模型。
部署需要一定的c++操作水平及工具
這幾天試了試openvino,一開始win10系統老是安裝不上,到換ubuntu系統,玩到最后發現目前openvino還不支持yolov5的模型轉換。
so sad
搞了好幾天發現openvino暫時行不通。
win10下載的make瘋狂報錯導致我win下無法實現tensorRT轉換部署,換了虛擬機沒cuda搞不了,很糟糕。
記下2020·11·22,搞搞停停 我終于完整的完成tensorrt部署,過幾天閑下來就更新。
記下2020·12·18,我們取得了第三屆英偉達sky hackathon比賽的第一,至少證明了我這一年多的學習和認識還算正確。
此篇主要是用于部署含cuda的英偉達GPU移動設備,如果是想部署CPU設備以及ncnn的使用可以參考我的筆記四yolov5筆記(4)——CPU部署以及NCNN,但是筆記四不像筆記三那樣真的一步一步操作下來,筆記四只講思路和一些關鍵的代碼操作,有一點閱讀門檻。建議還是先把筆記三看一遍,再閱讀筆記四。
1.pt轉ONNX、ML、TorchScript
安裝ONNX
在yolov5文件夾下運行
pip install -r requirements.txt onnx # install requirements.txt and ONNX轉換文件
在這里,我以轉換官方的yolov5s.pt模型文件為例
在yolov5文件夾下運行
會報錯No module named "utils",原因是utils這個文件夾跟models文件夾同級,所以export.py文件找不到這個文件
解決辦法:將export.py從model文件夾移到上一級yolov5文件夾中
換好后小改下命令行輸入
安裝coremltools
pip install coremltools安裝pankaging
pip install packaging安裝完packaging后,似乎還會遇到一個小問題,是關于轉換ML文件的問題,但忘記了具體是什么問題。大家可以自己摸索下,我記得不是很難,很簡單就能解決的。
成功
應該會多出現三個文件
分別是ONNX文件、ML文件、torchscript文件
你也可以使用Netron來查看你的ONNX文件模型
使用Netron
其實netron現已支持大部分格式的模型文件,都是可以查看的。
PaddlePaddle、OpenVINO、TensorFlow 、Caffe…
安裝netron
進入python,運行netron.start()
import netron netron.start('[FILE]')
2.Jetson nano的部署
準備軟硬件
一個Jetson nano 4GB(據說2GB和4GB會有些不同,所以我不保證2GB照我的方法能部署成功)
下載官方的jetpack_v4.4.1
64GB 的tf卡(他鏡像就30G左右所以建議64GB起步)
- 下載網址https://developer.nvidia.com/embedded/jetpack
- 下載百度云 4GB的鏡像,2GB的鏡像就自己下一下吧
鏈接:https://pan.baidu.com/s/1l-1UndyjtNYeGQTpQxKDeQ
提取碼:4e67
USB無線網卡(Jetson nano不自帶網絡,需額外購買無線網卡)
DC 5v 4A 電源(建議使用這個供電,用5v 2A 的電源接口,常常會導致功率不足而關機)
風扇(不加風扇的話散熱器摸起來就賊燙,加了就冰冰涼,雖然運行上沒啥明顯區別,加了求個心安吧)
大屏顯示器、機械鍵盤、鼠標
!!!有個注意事項就是使用5V 4A電源供電的話,需要在圖片位置安置一個跳線帽。
配置Jetson nano
1.上傳鏡像
使用Jetpack 官方的NVIDIA SDK Manager安裝鏡像
2.常規配置
- 插上USB無線網卡連接wifi
- 安裝vim(個人習慣,可安裝可不安裝) 代碼:sudo apt-get install vim
- 換源 網上有很多可行的教程,這里就不多說了)
Jetson Nano更換軟件源 - 啟用cuda、安裝pip3
Jetson Nano配置與使用(5)cuda測試及tensorflow gpu安裝 - 安裝pycuda
jetson nano安裝pycuda!!!
到這一步Jetson nano的環境就基本配置好了
如果一切正常的話,你的Jetson nano里的配置應該是下面這個樣子:
- NVIDIA Jetpack 4.4DP
- Ubuntu 18.04 L4T
- Python 3.6.9
- TensorRT 7.1
- CUDA 10.2
- NVIDIA Transfer Learning Toolkit 2.0
- Opencv 4.1.1
- Numpy 1.16.1
對于我的方法這些庫是必須的,版本我不能說一定是我這樣的吧,但你一旦出現一些奇怪的問題,請對照下我的環境。
3.下載yolov5、tensorrtx
git clone https://github.com/wang-xinyu/tensorrtx.git git clone https://github.com/ultralytics/yolov5.git生成trt引擎
yolov5官方教程:https://github.com/wang-xinyu/tensorrtx/tree/master/yolov5
接下去我主要是按照官方教程給大家作中文翻譯示范
1.生成wts文件
這一步可以在x86系統上完成。
首先你得有yolov5的模型文件,我上一篇有講,我這里使用yolov5s.pt訓練出來的best.pt文件來進行下面的操作。
復制 tensorrtx/yolov5/gen_wts.py文件 到 yolov5 文件夾中
5.0的tensorrtx修改了這一python文件
只需要輸入一次文件路徑即可生成對應文件。
python3 gen_wts.py weights/yolov5s.pt這樣就會在weights文件夾中生成一個yolov5s.wts文件。
2.build
這一步是生成部署引擎,必須來到部署該引擎的硬件設備上進行。
就像我這里模型是想在Jetson nano上部署,所以這一步就必須在Jetson nano上進行build。在此之前的有關yolov5的操作都可在x86的系統上完成。
將yolov5s.wts文件放到tensorrtx/yolov5文件夾中,
來到tensorrtx/yolov5文件夾中,查看yolov5.cpp中的模型是s。
!!!在最新的4.0版本中,作者優化了這一API,不再需要這一步了!!!
在yolov5.cpp文件中還可以修改fp16還是fp32 int8、device(選擇哪一個GPU設備)、nms_thresh(nms的閾值)、conf_thresh(conf的置信度)、batch_size(批次大小)
這里我對于其他的參數全部默認
打開yololayer.h文件,修改他的num總數,根據你訓練模型的類個數來,我這個best.pt訓練的是四個種類的目標檢測模型,所以我寫四(并不是我上一篇文章中的檢測紅細胞模型的pt文件)
除此之外,我們還可以修改輸入圖片的尺寸,但必須是32的倍數。縮小輸入尺寸可以一定程度上加快推理速度。
確保tensorrtx/yolov5文件下有你的wts文件,并且相應地修改了yolov5.cpp
文件和yolovlayer.h文件。
然后在tensorrtx/yolov5文件夾下依次執行下面的代碼
如果你是通過修改每一層卷積的寬度和深度來達到自定義的模型的話,就可以直接使用下面的命令來達成生成引擎,這是我認為4.0的這個版本最大的升級點了!!!
sudo ./yolov5 -s yolov5_custom.wts yolov5.engine c 0.17 0.25我一般縮小寬度和深度來達到剪裁模型,加快運行速度的作用。這一api優化讓我的調試十分的方便。
v5.0的tensorrtx庫更新適配了yolov5的p6模型,如果你用的是p6模型訓練,可以使用下面的命令。
到這一步,我們便通過tensorrt生成了基于C++的engine部署引擎文件
你可以放幾張用來測試,將yolov5 /data文件夾中的images文件夾整個復制到tensorrtx/yolov5文件夾,在build文件夾里執行下面的代碼。
到一步我們已經算是完成了Jetson nano的部署,但你可能會發現在build中的圖片幾乎沒有框。
這是因為s模型所產生的置信度一般在0.2-0.4之間,而我們之前在設置yolov5.cpp文件時把置信度conf_thresh設置在0.5了,也就是說低于0.5的檢測框都被我們排除了,所以檢測結果空空蕩蕩。
3.python調用
編輯yolov5_trt.py文件
這里不管在哪個系統上修改的都一樣,因為此時此刻nano不在身邊,所以我就直接用win來演示了。
注釋掉import torch和import torchvision,因為在nano上安裝這兩個庫是有些麻煩的特別是torchvision。
當然你也可以去試試安裝這兩個庫,網上的一些教程我有試過是可以成功,就是麻煩。
INPUT_W和INPUT_H根據你自己之前設置的來,我build時是寫608,所以這里也是608。
CONF_THRESH 與 IOU_THRESHOLD 可根據最后的顯示效果返回來修改他,暫且不調整。
第223行,讓y直接等于np.zeros_like(x),這里是創建一個和x形狀相同的全0矩陣。因為不用torch庫,所以用ndarray表示。
第258行,直接注釋掉這句話,因為我們既不想用torch,numpy也不存在cuda方法。
如果你在nano上成功安裝torch和torchvison這兩個庫并使用他們,最好要把這行的cuda方法給關掉,我嘗試過很多次,在nano上使用cuda方法會使程序卡死,輕則過老久給你報錯,重則需拔電重啟。
第273行注釋掉,因為這一行使用到了torchvision。他用torchvision庫中的nms方法來完成非極大值抑制。
后面三行去掉cpu方法,因為ndarray沒有這個方法。
往YoLov5TRT這個類中加入一個方法,這是用numpy的方式實現nms,注意空格對齊。
現在我們把nms的結果賦值給indices變量,如下圖所示改寫post_process函數
來到main函數這里,修改成你build出來的引擎的相對路徑
修改成你訓練時相應的標簽,記住一定要和你訓練時的標簽順序一致,因為yolo識別出來的是0,1,2,3。他是把這個當作列表索引號來找到對應的標簽名。
然后將要檢測的圖片一張一張地送進入就可以檢測了。
到這一步,我們Ctrl+S保存代碼,在命令行上運行這個python腳本,就可以得到檢測結果。如果你覺得一些框的置信度太低導致識別地不對,可以去提高我上面說的CONF_THRESH。
4.視頻檢測
在之前python文件或c++文件上加入opencv的API即可。
接下來我將講下python調用的流程,也可算是對官方的文件一個過程解釋和重構。
導入必要的庫
設置基本的參數和類別名稱
INPUT_W = 608 INPUT_H = 608 CONF_THRESH = 0.2 IOU_THRESHOLD = 0.4categories = ['vehicle','bicyle','pedestrain','road_sign']定義畫框函數
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 objectcolor: color to draw rectangle, such as (0,255,0)label: strline_thickness: intreturn:no return"""tl = (line_thickness or round(0.002 * (img.shape[0] + img.shape[1]) / 2) + 1) # line/font thicknesscolor = 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 thicknesst_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA) # filledcv2.putText(img,label,(c1[0], c1[1] - 2),0,tl / 3,[225, 255, 255],thickness=tf,lineType=cv2.LINE_AA,)def draw_boxes(image_raw, result_boxes, result_scores, result_classid):for i in range(len(result_boxes)):box = result_boxes[i]plot_one_box(box,image_raw,label="{}:{:.2f}".format(categories[int(result_classid[i])], result_scores[i]),)return image_raw定義yolov5轉trt的類
class YoLov5TRT(object):"""description: A YOLOv5 class that warps TensorRT ops, preprocess and postprocess ops."""def __init__(self, engine_file_path):# Create a Context on this device,self.cfx = cuda.Device(0).make_context()stream = cuda.Stream()TRT_LOGGER = trt.Logger(trt.Logger.INFO)runtime = trt.Runtime(TRT_LOGGER)# Deserialize the engine from filewith open(engine_file_path, "rb") as f:engine = runtime.deserialize_cuda_engine(f.read())context = engine.create_execution_context()host_inputs = []cuda_inputs = []host_outputs = []cuda_outputs = []bindings = []for binding in engine:size = trt.volume(engine.get_binding_shape(binding)) * engine.max_batch_sizedtype = trt.nptype(engine.get_binding_dtype(binding))# Allocate host and device buffershost_mem = cuda.pagelocked_empty(size, dtype)cuda_mem = cuda.mem_alloc(host_mem.nbytes)# Append the device buffer to device bindings.bindings.append(int(cuda_mem))# Append to the appropriate list.if engine.binding_is_input(binding):host_inputs.append(host_mem)cuda_inputs.append(cuda_mem)else:host_outputs.append(host_mem)cuda_outputs.append(cuda_mem)# Storeself.stream = streamself.context = contextself.engine = engineself.host_inputs = host_inputsself.cuda_inputs = cuda_inputsself.host_outputs = host_outputsself.cuda_outputs = cuda_outputsself.bindings = bindings# 釋放引擎,釋放GPU顯存,釋放CUDA流def __del__(self):print("delete object to release memory")def infer(self, image_raw):threading.Thread.__init__(self)# Make self the active context, pushing it on top of the context stack.self.cfx.push()# Restorestream = self.streamcontext = self.contextengine = self.enginehost_inputs = self.host_inputscuda_inputs = self.cuda_inputshost_outputs = self.host_outputscuda_outputs = self.cuda_outputsbindings = self.bindings# Do image preprocessinput_image, image_raw, origin_h, origin_w = self.preprocess_image(image_raw)# Copy input image to host buffernp.copyto(host_inputs[0], input_image.ravel())# Transfer input data to the GPU.cuda.memcpy_htod_async(cuda_inputs[0], host_inputs[0], stream)# Run inference.context.execute_async(bindings=bindings, stream_handle=stream.handle)# Transfer predictions back from the GPU.cuda.memcpy_dtoh_async(host_outputs[0], cuda_outputs[0], stream)# Synchronize the streamstream.synchronize()# Remove any context from the top of the context stack, deactivating it.self.cfx.pop()# Here we use the first row of output in that batch_size = 1output = host_outputs[0]# Do postprocessresult_boxes, result_scores, result_classid = self.post_process(output, origin_h, origin_w)return image_raw, result_boxes, result_scores, result_classiddef destroy(self):# Remove any context from the top of the context stack, deactivating it.self.cfx.pop()def preprocess_image(self, image_raw):"""description: Read an image from image path, convert it to RGB,resize and pad it to target size, normalize to [0,1],transform to NCHW format.param:input_image_path: str, image pathreturn:image: the processed imageimage_raw: the original imageh: original heightw: original width"""h, w, c = image_raw.shapeimage = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB)# Calculate widht and height and paddingsr_w = INPUT_W / wr_h = INPUT_H / hif r_h > r_w:tw = INPUT_Wth = int(r_w * h)tx1 = tx2 = 0ty1 = int((INPUT_H - th) / 2)ty2 = INPUT_H - th - ty1else:tw = int(r_h * w)th = INPUT_Htx1 = int((INPUT_W - tw) / 2)tx2 = INPUT_W - tw - tx1ty1 = ty2 = 0# Resize the image with long side while maintaining ratioimage = cv2.resize(image, (tw, th))# Pad the short side with (128,128,128)image = cv2.copyMakeBorder(image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (128, 128, 128))image = image.astype(np.float32)# Normalize to [0,1]image /= 255.0# HWC to CHW format:image = np.transpose(image, [2, 0, 1])# CHW to NCHW formatimage = np.expand_dims(image, axis=0)# Convert the image to row-major order, also known as "C order":image = np.ascontiguousarray(image)return image, image_raw, h, wdef xywh2xyxy(self, origin_h, origin_w, x):"""description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-rightparam:origin_h: height of original imageorigin_w: width of original imagex: A boxes tensor, each row is a box [center_x, center_y, w, h]return:y: A boxes tensor, each row is a box [x1, y1, x2, y2]"""# y = torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x)y = np.zeros_like(x)r_w = INPUT_W / origin_wr_h = INPUT_H / origin_hif r_h > r_w:y[:, 0] = x[:, 0] - x[:, 2] / 2y[:, 2] = x[:, 0] + x[:, 2] / 2y[:, 1] = x[:, 1] - x[:, 3] / 2 - (INPUT_H - r_w * origin_h) / 2y[:, 3] = x[:, 1] + x[:, 3] / 2 - (INPUT_H - r_w * origin_h) / 2y /= r_welse:y[:, 0] = x[:, 0] - x[:, 2] / 2 - (INPUT_W - r_h * origin_w) / 2y[:, 2] = x[:, 0] + x[:, 2] / 2 - (INPUT_W - r_h * origin_w) / 2y[:, 1] = x[:, 1] - x[:, 3] / 2y[:, 3] = x[:, 1] + x[:, 3] / 2y /= r_hreturn ydef nms(self, boxes, scores, iou_threshold=IOU_THRESHOLD):x1 = boxes[:, 0]y1 = boxes[:, 1]x2 = boxes[:, 2]y2 = boxes[:, 3]areas = (y2 - y1 + 1) * (x2 - x1 + 1)scores = scoreskeep = []index = scores.argsort()[::-1]while index.size > 0:i = index[0] # every time the first is the biggst, and add it directlykeep.append(i)x11 = np.maximum(x1[i], x1[index[1:]]) # calculate the points of overlapy11 = np.maximum(y1[i], y1[index[1:]])x22 = np.minimum(x2[i], x2[index[1:]])y22 = np.minimum(y2[i], y2[index[1:]])w = np.maximum(0, x22 - x11 + 1) # the weights of overlaph = np.maximum(0, y22 - y11 + 1) # the height of overlapoverlaps = w * hious = overlaps / (areas[i] + areas[index[1:]] - overlaps)idx = np.where(ious <= iou_threshold)[0]index = index[idx + 1] # because index start from 1return keepdef post_process(self, output, origin_h, origin_w):"""description: postprocess the predictionparam:output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...]origin_h: height of original imageorigin_w: width of original imagereturn:result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2]result_scores: finally scores, a tensor, each element is the score correspoing to boxresult_classid: finally classid, a tensor, each element is the classid correspoing to box"""# Get the num of boxes detectednum = int(output[0])# Reshape to a two dimentional ndarraypred = np.reshape(output[1:], (-1, 6))[:num, :]# to a torch Tensor# pred = torch.Tensor(pred).cuda()# Get the boxesboxes = pred[:, :4]# Get the scoresscores = pred[:, 4]# Get the classidclassid = pred[:, 5]# Choose those boxes that score > CONF_THRESHsi = scores > CONF_THRESHboxes = boxes[si, :]scores = scores[si]classid = classid[si]# Trandform bbox from [center_x, center_y, w, h] to [x1, y1, x2, y2]boxes = self.xywh2xyxy(origin_h, origin_w, boxes)# Do nms# indices = torchvision.ops.nms(boxes, scores, iou_threshold=IOU_THRESHOLD).cpu()# result_boxes = boxes[indices, :].cpu()# result_scores = scores[indices].cpu()# result_classid = classid[indices].cpu()# return result_boxes, result_scores, result_classidindices = self.nms(boxes, scores, IOU_THRESHOLD)result_boxes = boxes[indices, :]result_scores = scores[indices]result_classid = classid[indices]return result_boxes, result_scores, result_classid定義檢測圖片的函數,它接收一張圖片和編譯好的trt文件,推理出框的坐標(中心點x,y,長,寬)、置信度、類別名稱,并使用前面的畫框函數在此圖片上畫出這個框。
def detect_one(img, yolov5_wrapper):full_scrn = Falsetic = time.clock()##開始檢測,并將結果寫到result.jpg中img, result_boxes, result_scores, result_classid = yolov5_wrapper.infer(img)toc = time.clock()curr_fps = (toc - tic)print("boxes: "+str(result_boxes))print("clss: "+str(result_classid))print("confs: "+str(result_scores))img = draw_boxes(img, result_boxes, result_scores, result_classid)cv2.imwrite("result.jpg",img)print("time: "+str(curr_fps)+"(sec)")檢測圖片,filename改為相對路徑,引擎的相對路徑,可放在main里直接運行
def main_one():filename = "1.jpg" img = cv2.imread(filename)# load custom pluginsPLUGIN_LIBRARY = "yolov5s/libmyplugins.so"ctypes.CDLL(PLUGIN_LIBRARY)engine_file_path = "yolov5s/yolov5s.engine"# a YoLov5TRT instanceyolov5_wrapper = YoLov5TRT(engine_file_path)print("start detection!")detect_one(img, yolov5_wrapper)cv2.destroyAllWindows()print("finish!")顯示圖片結果
from IPython.display import Image main_one() Image("result.jpg")定義檢測視頻的函數,它接收一個視頻和編譯好的trt文件,按幀推理出框的坐標(中心點x,y,長,寬)、置信度、類別名稱,并使用前面的畫框函數在此圖片上畫出這個框。
def detect_video(video, yolov5_wrapper):full_scrn = Falsefps = 0.0tic = time.time()frame_width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))frame_height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))fps = video.get(cv2.CAP_PROP_FPS)#print(str(frame_width)+str(frame_height))##定義輸入編碼fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')videoWriter = cv2.VideoWriter('result.AVI', fourcc, fps, (frame_width,frame_height))##開始循環檢測,并將結果寫到result.mp4中while True:ret,img = video.read()if img is not None:img, result_boxes, result_scores, result_classid = yolov5_wrapper.infer(img)img = draw_boxes(img, result_boxes, result_scores, result_classid)videoWriter.write(img)toc = time.time()curr_fps = 1.0 / (toc - tic)fps = curr_fps if fps == 0.0 else (fps*0.95 + curr_fps*0.05)tic = tocprint("\rfps: "+str(fps),end="")else:break檢測視頻,filename改為相對路徑,引擎的相對路徑,可放在main里直接運行
def main_loop():filename = "video2.mp4"video = cv2.VideoCapture(filename)# load custom pluginsPLUGIN_LIBRARY = "yolov5x/libmyplugins.so"ctypes.CDLL(PLUGIN_LIBRARY)engine_file_path = "yolov5x/yolov5x.engine"# a YoLov5TRT instanceyolov5_wrapper = YoLov5TRT(engine_file_path)print("start detection!")detect_video(video, yolov5_wrapper)video.release()cv2.destroyAllWindows()print("\nfinish!")顯示視頻,先運行main_loop()函數,然后在命令行中轉碼,最后在python中顯示,或者可以直接打開。
main_loop() # 下面兩行代碼是在命令行中運行 rm result-ffmpeg4.mp4 ffmpeg -i result.AVI -vcodec libx264 -f mp4 result-ffmpeg4.mp4 from IPython.display import Video Video("result-ffmpeg4.mp4")OK,我終于有空更新攝像頭檢測了,由于現在更新時手上只有CSI攝像頭,所以我的攝像頭代碼以使用CSI攝像頭為止,usb攝像頭可以自己改一改。
def detect_camera(camera, yolov5_wrapper):##開始循環檢測,并將結果寫到result.mp4中while True:#ret,img = camera.read() # usb攝像頭用這個img = camera.read()img, result_boxes, result_scores, result_classid = yolov5_wrapper.infer(img)img = draw_boxes(img, result_boxes, result_scores, result_classid)cv2.namedWindow("result", 0)cv2.resizeWindow("result", 640, 480)cv2.imshow("result", img)if cv2.waitKey(1) == ord('q'):break from jetcam.csi_camera import CSICamera def main_camera():# camera = cv2.VideoCapture(0) # usb攝像頭用這個,也可以用jetcam中的usb接口camera = CSICamera(capture_device=0, width=224, height=224)# load custom pluginsPLUGIN_LIBRARY = "yolov5x/libmyplugins.so"ctypes.CDLL(PLUGIN_LIBRARY)engine_file_path = "yolov5x/yolov5x.engine"# YoLov5TRT instanceyolov5_wrapper = YoLov5TRT(engine_file_path)print("start detection!")detect_camera(camera, yolov5_wrapper)# camera.release() 使用cv方法打開攝像頭才需要這句cv2.destroyAllWindows()print("\nfinish!")定義好攝像頭檢測的函數后便可直接使用
main_camera()至此,寫寫停停快半年,我算是完整地更新完嵌入式邊緣設備的yolov5部署了。之后并不會更新安卓和IOS設備的部署,一來我沒有這種需求,二是網上此類教程我感覺還蠻多的。最初寫這個教程的一個原因就是網上找不到好的詳細的移動設備部署,怕自己以后忘記怎么操作才寫的這個教程。
感謝各位的閱讀點贊收藏提問和解答,這是我最近幾次更新的全部動力,有問題可以底下留言或者私信。
yolov5筆記(1)——安裝pytorch_GPU(win10+anaconda3)
yolov5筆記(2)——訓練自己的數據模型(隨6.0更新)
yolov5筆記(3)——移動端部署自己的模型(隨5.0更新)
yolov5筆記(4)——CPU部署以及NCNN
總結
以上是生活随笔為你收集整理的yolov5笔记(3)——移动端部署自己的模型(随5.0更新)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嵌入式工具库 -- 脱机离线下载器(ST
- 下一篇: python获取期货实时行情_量化投资者