使用 google colab 的 python 代码工作方式

问题描述

我有一个带有 yolov4 的对象跟踪 python 代码,它在我的计算机上运行良好。 但是我的笔记本电脑上没有适合的 GPU,而且我的输出视频的 fps 很低。 我试图用 cuda 用 gpu 重建 opencv,但我的卡不支持

colab 是我最后一次更改,我从昨晚开始一直在搜索它,但无论如何都没有进展。

你能告诉我一些如何使用 colab 做到这一点的方法吗?

这是我的代码

import cv2 as cv
import numpy as np
import time
import math

class EuclideandistTracker:
    def __init__(self):
        # Store the center positions of the objects
        self.center_points = {}
        # Keep the count of the IDs
        # each time a new object id detected,the count will increase by one
        self.id_count = 0


    def update(self,objects_rect):
        # Objects Boxes and ids
        objects_bbs_ids = []

        # Get center point of new object
        for rect in objects_rect:
            x,y,w,h = rect
            cx = (x + x + w) // 2
            cy = (y + y + h) // 2

            # Find out if that object was detected already
            same_object_detected = False
            for id,pt in self.center_points.items():
                dist = math.hypot(cx - pt[0],cy - pt[1])

                if dist < 25 or pt[1] > 350 :
                    self.center_points[id] = (cx,cy)
                    #print(self.center_points)
                    objects_bbs_ids.append([x,h,id])
                    same_object_detected = True
                    break

            # New object is detected we assign the ID to that object
            if same_object_detected is False:
                self.center_points[self.id_count] = (cx,cy)
                objects_bbs_ids.append([x,self.id_count])
                self.id_count += 1

        # Clean the dictionary by center points to remove IDS not used anymore
        new_center_points = {}
        for obj_bb_id in objects_bbs_ids:
            _,_,object_id = obj_bb_id
            center = self.center_points[object_id]
            new_center_points[object_id] = center

        # Update dictionary with IDs not used removed
        self.center_points = new_center_points.copy()
        return objects_bbs_ids


# Create tracker object
tracker = EuclideandistTracker()

# Load Yolo
net = cv.dnn.readNet("yolov4-tiny_best.weights","yolov4-tiny.cfg")

net.setPreferableBackend(cv.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv.dnn.DNN_TARGET_CUDA)
# print(cv.cuda.getCudaEnabledDeviceCount())
           
classes = []
with open("obj.names","r") as f:
    classes = [line.strip() for line in f.readlines()]
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]

# Loading video
cap = cv.VideoCapture("test2.mp4")
cap.set(3,1280) # set video widht
cap.set(4,720) # set video height

font = cv.FONT_HERShey_COMPLEX_SMALL
starting_time = time.time()
frame_id = 0
toplam = 0
print("\033[H\033[J") 
while True:
    # Get frame
    _,frame = cap.read()
    frame_id += 1
    height,width,channels = frame.shape

    # Detecting objects
    blob = cv.dnn.blobFromImage(frame,0.00261,(416,416),(0,0),True,crop=False)
    net.setInput(blob)
    
    outs = net.forward(output_layers)
    
    result = []
    Boxes = []
    liste = []
    for out in outs:
        for detection in out:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.7:
                # 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,h])

    Boxes_ids = tracker.update(Boxes)
    
    eklenecekler = []
    filtered =[]
    for i in range(len(Boxes_ids)):
        if Boxes_ids[i][4] not in eklenecekler:
            eklenecekler.append(Boxes_ids[i][4])
            filtered.append(Boxes_ids[i])
   
    for Box_id in filtered:
            x,id = Box_id
            cv.rectangle(frame,(x,y+h-20),(x+30,y+h),255),-1)
            cv.putText(frame,str(id+1),y + h),font,1,(255,255,1)
            cv.rectangle(frame,y),(x + w,2)
   

    # For fps
    elapsed_time = time.time() - starting_time
    fps = frame_id / elapsed_time
    
    
    
    #total car count
    try:
        _,value = max(filtered,key=lambda item: item[4])
        if value > toplam:
            toplam = value
    except:
        pass
        
    cv.line(frame,350),(1280,2)
    
    #Some texts
    cv.putText(frame,"FPS: " + str(round(fps,2)),(5,156),2)
    cv.putText(frame,"NAZIM CORAKLI",(600,70),str(toplam+1),(1200,2,2)
    
    #Final
    cv.imshow("Awsome Car Counting",frame)
    
    # Press 'ESC' for exiting video
    k = cv.waitKey(1) & 0xff 
    if k == 27:
        break
    if k == ord('p'):
        cv.waitKey(-1) #wait until any key is pressed

cap.release()
cv.destroyAllWindows()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)