如何使用GPU在Visual Studio 2022中使用OpenCV运行YOLOv3算法



我是计算机视觉和物体检测的新手,我遇到了这个关于使用OpenCV、预训练的YOLOv3模型和coco数据集对视频执行物体检测的练习。我目前正在使用visual studio 2022和最新的opencv python以及所需的文件,如weight、cfg和name文件。然而,该算法有效,当显示输出视频时,处理速度较低。我在网上搜索,大多数人都建议使用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绑定。如果您没有,您可以检查此项,因为您使用的是Visual Studio,但它适用于Windows。

如果你使用的是linux,你可以在这里查看

步骤2

在开始循环之前放入此代码

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

塔达,你完了!

最新更新