Jetson Nano AI入门(3)— 使用DetectNet进行目标检测

前面的图像识别示例输出了代表整个输入图像的类的概率。接下来我们将专注于目标检测(Objection Dectection),并通过提取它们的边界框来查找框架中各种目标的位置。与图像分类不同,目标检测网络能够每帧检测许多不同的对象。

图片

detectNet 对象接受图像作为输入,并输出检测到的边界框的坐标列表以及它们的类别和置信度值。detectNet 可用于 Python 和 C++。有关可供下载的各种预训练检测模型,请参见下文。使用的默认模型是在 MS COCO 数据集上训练的 91 类 SSD-Mobilenet-v2 模型,该模型使用 TensorRT 在 Jetson 上实现了实时推理性能。

网络CLI参数NetworkType enum目标分类
SSD-Mobilenet-v1ssd-mobilenet-v1SSD_MOBILENET_V191(COCO classes)
SSD-Mobilenet-v2ssd-mobilenet-v2SSD_MOBILENET_V291(COCO classes)
SSD-Inception-v2ssd-mobilenet-v1SSD_MOBILENET_V191(COCO classes)
DetectNet-COCO-Dogcoc-dogCOCO_DOG
DetectNet-COCO-Bottlecoc-bottleCOCO_BOTTLE瓶子
DetectNet-COCO-Chaircoc-chairCOCO_CHAIR椅子
DetectNet-COCO-AIrplanecoc-airplaneCOCO_AIRPLANE飞机
ped-100pednetPEDNET行人
multiped-500pednetPEDNET行人,行李
facenet-120facenetFACENET面部

注:要稍后再次运行 Model Downloader 工具,可以使用以下命令

$ cd jetson-inference/build$ ./download-models.sh

在Visual Studio Code里面新建.py文件,导入以下库

import jetson.inferenceimport jetson.utilsimport cv2import numpy as np
import time

设置摄像头窗口的尺寸:

width=1280height=720cam=jetson.utils.gstCamera(width,height,'/dev/video0')

其中dev/vidoe0为摄像头的标识符,可在命令行窗口下采用ls /dev查看。

设置图像识别网络为“ssd-mobilnet-v2”,阈值设为0.5。

net=jetson.inference.detectNet('ssd-mobilenet-v2',threshold=.5)

设置显示字体:

font=cv2.FONT_HERSHEY_SIMPLEX

主循环:

while True: 
    _,img = cam.read() 
    height=img.shape[0] 
    width=img.shape[1]

    frame=cv2.cvtColor(img,cv2.COLOR_BGR2RGBA).astype(np.float32)
    frame=jetson.utils.cudaFromNumpy(frame) 
    detections=net.Detect(frame,width,height)

    for detect in detections: 
      ID = detect.ClassID   
      top=detect.Top 
      left = detect.Left 
      bottom = detect.Bottom right = detect.Right
      item=net.GetClassDesc(ID)        
      print(item,top,left,bottom,right)        
      cv2.rectangle(img,(left,top),(right,bottom),(0,255,255),2)
                  
      cv2.putText(img,item,(0,30),font,1,(0,0,255),2) 
      cv2.imshow('detCam',img) 
      cv2.moveWindow('detCam',0,0)

按”q”键退出循环:

if cv2.waitKey(1)==ord('q'): break

关闭摄像头和窗口:

cam.release()cv2.destroyAllWindows()

右键单击“在终端运行Python文件”,ssd-mobilenet检测到了摄像头中的矿泉水瓶,并用方框表示出来。

图片