0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

手把手教你使用LabVIEW OpenCV dnn实现物体识别(Object Detection)含源码

LabVIEW深度学习实战 来源:wangstoudamire 作者:wangstoudamire 2023-03-10 15:58 次阅读

前言

今天和大家一起分享如何使用LabVIEW调用pb模型实现物体识别,本博客中使用的智能工具包可到主页置顶博客LabVIEW AI视觉工具包(非NI Vision)下载与安装教程中下载

一、物体识别算法原理概述

1、物体识别的概念

物体识别也称 目标检测 ,目标检测所要解决的问题是目标在哪里以及其状态的问题。但是,这个问题并不是很容易解决。形态不合理,对象出现的区域不确定,更不用说对象也可以是多个类别。**

**在这里插入图片描述

目标检测用的比较多的主要是RCNN,spp- net,fast- rcnn,faster- rcnn;YOLO系列,如YOLOV3和YOLOV4;除此之外还有SSD,ResNet等。

2、Yolo算法原理概述

Yolo的识别原理简单清晰。对于输入的图片,将整张图片分为7×7(7为参数,可调)个方格。当某个物体的中心点落在了某个方格中,该方格则负责预测该物体。每个方格会为被预测物体产生2(参数,可调)个候选框并生成每个框的置信度。最后选取置信度较高的方框作为预测结果。

在这里插入图片描述

二、opencv调用darknet物体识别模型(yolov3/yolov4)

相关源码及模型在darknt文件夹下

在这里插入图片描述

使用darknet训练yolo的模型,生成weights文件。使用opencv调用生成的模型

1、darknet模型的获取

文件含义:

  • **cfg文件:模型描述文件 **
  • weights文件:模型权重文件

Yolov3获取链接:

https://github.com/pjreddie/darknet/blob/master/cfg/yolov3.cfg

https://pjreddie.com/media/files/yolov3.weights

Yolov4获取链接:

https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.cfg

https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights

2、python调用darknet模型实现物体识别

(1)dnn模块调用darknet模型

net = cv2.dnn.readNetFromDarknet("yolov3/yolov3.cfg", "yolov3/yolov3.weights")

(2)获取三个输出端的LayerName

使用getUnconnectedOutLayer获取三个只有输入,没有输出的层的名字,Yolov3的三个输出端层名为:['yolo_82', 'yolo_94', 'yolo_106']

def getOutputsNames(net):
    # Get the names of all the layers in the network
    layersNames = net.getLayerNames()
    # Get the names of the output layers, i.e. the layers with unconnected outputs
    return [layersNames[i - 1] for i in net.getUnconnectedOutLayers()]

**(3)图像预处理 **

使用blobFromImage将图像转为image

Size=(416,416)或(608,608)

Scale=1/255

Means=[0,0,0]

blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), [0,0,0], 1, crop=False)

(4)推理

使用net.forward(multiNames)获取多个层的结果,其中getOutputsNames(net)=['yolo_82', 'yolo_94', 'yolo_106']

net.setInput(blob)
outs = net.forward(getOutputsNames(net))

**(5)后处理(postrocess) **

获取的结果(outs)里面有三个矩阵(out),每个矩阵的大小为85*n,n表示检测到了n个物体,85的排列顺序是这样的:

  • 第0列代表物体中心x在图中的位置(0~1)
  • 第1列表示物体中心y在图中的位置(0~1)
  • 第2列表示物体的宽度
  • 第3列表示物体的高度
  • 第4列是置信概率,值域为[0-1],用来与阈值作比较决定是否标记目标
  • 第5~84列为基于COCO数据集的80分类的标记权重,最大的为输出分类。使用这些参数保留置信度高的识别结果(confidence>confThreshold)
def postprocess(frame, outs):
    frameHeight = frame.shape[0]
    frameWidth = frame.shape[1]
    classIds = []
    confidences = []
    boxes = []
    classIds = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            classId = np.argmax(scores)
            confidence = scores[classId]
            if confidence > confThreshold:
                center_x = int(detection[0] * frameWidth)
                center_y = int(detection[1] * frameHeight)
                width = int(detection[2] * frameWidth)
                height = int(detection[3] * frameHeight)
                left = int(center_x - width / 2)
                top = int(center_y - height / 2)
                classIds.append(classId)
                confidences.append(float(confidence))
                boxes.append([left, top, width, height])
    print(boxes)
    print(confidences)

**(6)后处理(postrocess) **

使用NMSBoxes函数过滤掉重复识别的区域。

indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold)  
    for i in indices:
        box = boxes[i]
        left = box[0]
        top = box[1]
        width = box[2]
        height = box[3]
        drawPred(classIds[i], confidences[i], left, top, left + width, top + height)

(7)画出检测到的对象

def drawPred(classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 0, 255))
     
    label = '%.2f' % conf
         
    # Get the label for the class name and its confidence
    if classes:
        assert(classId < len(classes))
        label = '%s:%s' % (classes[classId], label)

    #Display the label at the top of the bounding box
    labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
    top = max(top, labelSize[1])
    cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255))

(8)完整源码及检测结果(cv_call_yolo.py)

import cv2
cv=cv2
import numpy as np
import time
net = cv2.dnn.readNetFromDarknet("yolov3/yolov3.cfg", "yolov3/yolov3.weights")
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

confThreshold = 0.5  #Confidence threshold
nmsThreshold = 0.4   #Non-maximum suppression threshold
frame=cv2.imread("dog.jpg")
classesFile = "coco.names";
classes = None
with open(classesFile, 'rt') as f:
    classes = f.read().rstrip('\\\\\\\\\\\\\\\\n').split('\\\\\\\\\\\\\\\\n')

def getOutputsNames(net):
    # Get the names of all the layers in the network
    layersNames = net.getLayerNames()
    # Get the names of the output layers, i.e. the layers with unconnected outputs
    return [layersNames[i - 1] for i in net.getUnconnectedOutLayers()]
print(getOutputsNames(net))
# Remove the bounding boxes with low confidence using non-maxima suppression

def postprocess(frame, outs):
    frameHeight = frame.shape[0]
    frameWidth = frame.shape[1]
    classIds = []
    confidences = []
    boxes = []
    # Scan through all the bounding boxes output from the network and keep only the
    # ones with high confidence scores. Assign the box's class label as the class with the highest score.
    classIds = []
    confidences = []
    boxes = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            classId = np.argmax(scores)
            confidence = scores[classId]
            if confidence > confThreshold:
                center_x = int(detection[0] * frameWidth)
                center_y = int(detection[1] * frameHeight)
                width = int(detection[2] * frameWidth)
                height = int(detection[3] * frameHeight)
                left = int(center_x - width / 2)
                top = int(center_y - height / 2)
                classIds.append(classId)
                confidences.append(float(confidence))
                boxes.append([left, top, width, height])

    # Perform non maximum suppression to eliminate redundant overlapping boxes with
    # lower confidences.
    print(boxes)
    print(confidences)  
    indices = cv.dnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold) 
    for i in indices:
        #print(i)
        #i = i[0]
        box = boxes[i]
        left = box[0]
        top = box[1]
        width = box[2]
        height = box[3]
        drawPred(classIds[i], confidences[i], left, top, left + width, top + height)

    # Draw the predicted bounding box
def drawPred(classId, conf, left, top, right, bottom):
    # Draw a bounding box.
    cv.rectangle(frame, (left, top), (right, bottom), (0, 0, 255))
    label = '%.2f' % conf    
    # Get the label for the class name and its confidence
    if classes:
        assert(classId < len(classes))
        label = '%s:%s' % (classes[classId], label)
    #Display the label at the top of the bounding box
    labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)
    top = max(top, labelSize[1])
    cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255))
blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), [0,0,0], 1, crop=False)
t1=time.time()
net.setInput(blob)
outs = net.forward(getOutputsNames(net))
print(time.time()-t1)
postprocess(frame, outs)
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv.getTickFrequency())
cv.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))
cv2.imshow("result",frame)

在这里插入图片描述

3、LabVIEW调用darknet模型实现物体识别yolo_example.vi

(1)LabVIEW调用yolov3的方式及步骤和python类似,源码如下所示:

在这里插入图片描述

将待识别图片与yolo_example.vi置于同一路径下,即可进行物体识别

(2)识别结果如下:

在这里插入图片描述

4、LabVIEW实现实时摄像头物体识别(yolo_example_camera.vi)

(1)使用GPU加速

使用顺序结构检测神经网络推理的时间

在这里插入图片描述

比较使用GPU和不使用GPU两种情况下的推理速度

普通模式 :net.serPerferenceBackend(0),net.serPerferenceTarget(0)**

** Nvidia GPU模式 :net.serPreferenceBackend(5), net.serPerferenceTarget(6)**

**在这里插入图片描述

**注:普通的c++、python、LabVIEW版本的opencv,即便选了GPU模式也没用,程序仍然运行在CPU上,需要安装CUDA和CUDNN后重新从源码编译opencv **

(2)程序源码如下:

在这里插入图片描述

(3)物体识别结果如下:

在这里插入图片描述

注意,使用如上程序,可以点击STOP按钮,停止本次物体识别,也可勾选使用GPU进行加速

(4)使用GPU加速结果:

在这里插入图片描述

三、tensorflow的物体识别模型调用

相关源码及模型在tf1文件夹下

在这里插入图片描述

1、下载预训练模型并生成pbtxt文件

(1)下载ssd_mobilenet_v2_coco,下载地址如下:

http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v2_coco_2018_03_29.tar.gz

(2)解压后的文件内容

在这里插入图片描述

(3)根据pb模型生成pbtxt文件

运行 tf_text_graph_ssd.py以生成pptxt文件

在cmd中运行:

**python tf_text_graph_ssd.py --input ssd_mobilenet_v1_coco_2017_11_17/frozen_inference_graph.pb --config ssd_mobilenet_v1_coco_2017_11_17/ssd_mobilenet_v1_coco.config --output ssd_mobilenet_v1_coco_2017_11_17.pbtxt **

2、LabVIEW调用tensorflow模型推理并实现物体识别(callpb.vi)

(1)程序源码如下:

在这里插入图片描述

(2)运行结果如下:

在这里插入图片描述

四、项目源码及模型下载

链接: https://pan.baidu.com/s/1zwbLQe0VehGhsqNIHyaFRw?pwd=8888

**提取码:8888 **

总结拓展

**可以使用Yolov3训练自己的数据集,具体训练方法可参考博客

可实现案例:口罩佩戴识别、肺炎分类、CT等,如口罩佩戴检测

在这里插入图片描述

审核编辑 黄宇

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • LabVIEW
    +关注

    关注

    1936

    文章

    3620

    浏览量

    318556
  • 目标检测
    +关注

    关注

    0

    文章

    188

    浏览量

    15530
  • OpenCV
    +关注

    关注

    29

    文章

    615

    浏览量

    40919
  • 物体识别
    +关注

    关注

    0

    文章

    14

    浏览量

    7456
  • dnn
    dnn
    +关注

    关注

    0

    文章

    57

    浏览量

    8977
收藏 人收藏

    评论

    相关推荐

    【汇总篇】小草手把手教你 LabVIEW 串口仪器控制

    `课程推荐>>《每天1小时,龙哥手把手教您LabVIEW视觉设计》[hide]小草手把手教你 LabVIEW 串口仪器控制—生成
    发表于 02-04 10:45

    【视频汇总】小草大神手把手教你Labview技巧及源代码分享

    点击学习>>《龙哥手把手教你LabVIEW视觉设计》视频教程原创视频教程小草手把手教你LabVIEW
    发表于 05-26 13:48

    手把手教你LabVIEW仪器控制

    手把手教你LabVIEW仪器控制,串口学习
    发表于 12-11 12:00

    labview测试tensorflow深度学习SSD模型识别物体

    文件调用labview深度学习推理函数完成识别以上是识别动物和人等物体labview识别效果。
    发表于 08-16 17:21

    手把手教你如何一步一步实现人脸识别的门禁系统

    是一个人脸识别的门禁系统开源源码及论文,基本功能实现,但其教程较简略且有欠缺。本教程将从零开始,手把手教你如何一步一步
    发表于 12-14 06:44

    手把手教你写批处理-批处理的介绍

    手把手教你写批处理-批处理的介绍
    发表于 10-25 15:02 69次下载

    美女手把手教你如何装机(中)

    美女手把手教你如何装机(中) 再来是硬碟的部份,这款机壳还不错,可以旋转支架~
    发表于 01-27 11:14 1378次阅读

    美女手把手教你如何装机(下)

    美女手把手教你如何装机(下) 接著下来就是今天的重头戏,开核萝!~
    发表于 01-27 11:16 2890次阅读

    小草手把手教你LabVIEW仪器控制V1.0

    小草手把手教你LabVIEW仪器控制V1.0 ,感兴趣的小伙伴们可以看看。
    发表于 08-03 17:55 94次下载

    手把手教你安装Quartus II

    本章手把手把教你如何安装 Quartus II 软件 ,并将它激活 。此外 还有USB -Blaster下载器的驱动安装步骤 。
    发表于 09-18 14:55 9次下载

    手把手教你如何开始DSP编程

    手把手教你如何开始DSP编程。
    发表于 04-09 11:54 12次下载
    <b class='flag-5'>手把手</b><b class='flag-5'>教你</b>如何开始DSP编程

    手把手教你LabVIEW视觉设计

    手把手教你LabVIEW视觉设计手把手教你LabVIEW视觉设计
    发表于 03-06 01:41 2873次阅读

    手把手教你使用LabVIEW OpenCV DNN实现手写数字识别源码

    LabVIEW中如何使用OpenCV DNN模块实现手写数字识别
    的头像 发表于 03-08 16:10 1265次阅读

    手把手教你使用LabVIEW OpenCV dnn实现图像分类(源码

    使用LabVIEW OpenCV dnn实现图像分类
    的头像 发表于 03-09 13:37 919次阅读

    手把手教你学FPGA仿真

    电子发烧友网站提供《手把手教你学FPGA仿真.pdf》资料免费下载
    发表于 10-19 09:17 2次下载
    <b class='flag-5'>手把手</b><b class='flag-5'>教你</b>学FPGA仿真