我如何使用 GPU 在 Visual Studio 2022 年使用 OpenCV 运行 我的 YOLOv3 算法?

How do I run my YOLOv3 algorithm with OpenCV in Visual Studio 2022 using GPU?

我是计算机视觉和对象检测的新手,我遇到了这个关于使用 OpenCV、预训练的 YOLOv3 模型和 coco 数据集对视频执行对象检测的练习。我目前正在使用 visual studio 2022 和最新的 opencv-python 以及所需的文件,例如重量、cfg 和名称文件。该算法有效,但是,显示输出视频时的处理速度较低。网上搜了一下,大部分都建议用GPU。

在我当前的设置中,我有一个 CPU:Intel(R) Core(TM) i5-4570 @3.20GHzGPU : NVDIA GeForce GTX 650 Ti BOOST

我计划制作一个自定义数据集以供稍后训练。无论如何,我可以在 visual studio 2022 年使用 GPU 执行对象检测和训练吗?如果是这样,我需要执行哪些程序和步骤才能这样做?提前致谢。

python代码:

import cv2
import numpy as np

# Load YOLO
net = cv2.dnn.readNet("YOLO_COCO/yolov3.weights", "YOLO_COCO/yolov3.cfg")
classes = []
with open("YOLO_COCO/coco.names","r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]
colors = np.random.uniform(0, 255, size=(len(classes), 3))

# Load Video
cap = cv2.VideoCapture('videos/overpass.mp4')

while True:
    _, img = cap.read()

    height, width, channel = img.shape

    # Detecting Objects
    blob = cv2.dnn.blobFromImage(img, 1/255, (416,416), (0, 0, 0), swapRB=True, crop=False) 

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


    # Show information on the screen
    # Initialise variables
    class_ids = []
    confidences = [] 
    boxes = []

    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence>0.5:
                # Object detected
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] * width)
                h = int(detection[3] * height)

                # Rectangle coordinates
                x = int (center_x - w/2)
                y = int (center_y - h/2)

                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                class_ids.append(class_id)

    # Non Maximum Suppresion (Keep one box)
    indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.5, 0.4)

    # Label object
    font = cv2.FONT_HERSHEY_PLAIN
    for i in range (len(boxes)):
        if i in indexes:
            x, y, w, h = boxes[i]
            label = str(classes[class_ids[i]])
            confidence = str(round(confidences[i],2))
            color = colors[i]
            cv2.rectangle(img, (x,y), (x+w, y+h), color, 2)
            cv2.putText(img, label + "  " + confidence, (x, y+20), font, 1, color, 2)

    cv2.imshow("Video", img)
    key = cv2.waitKey(1)
    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()

步骤 1

确保您的 OpenCV 已经与 CUDA 绑定。如果你没有,你可以检查 this 因为你正在使用 Visual Studio 但那是 Windows.

如果您使用的是linux,您可以查看here

第 2 步

在开始循环之前放置这段代码

net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)

Tadaa,大功告成!