为什么我的程序一直试图占用所有可用的CPU

2024-06-17 19:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

正如您从上面看到的,进程一直在尝试尽可能多地占用cpu资源。在上面的图片上,我只使用相机源进行测试。正如你们在下面看到的,我为每台可用的相机重复每一个过程。起初我认为原因是我的cpu没有足够的功率,但增加了几个摄像头。事实上,没有一个摄像头是滞后的,所有的摄像头都与只有一个摄像头的fps差不多,这让我怀疑实际原因是什么,因为显然这不是由于CPU资源不足造成的。下面是我的主要节目

import cProfile
from multiprocessing import Process
import sys
import threading
import videoPlayerThreading as vpt
from objDect import objDect as od

def main(videoSource):
    obd = od( videoSources = videoSource, GPU=True )
    
    getFrame = vpt.getFrames(videoSource).start()
    showFrame = vpt.showFrames(getFrame.frame).start()

    getFrame.videoInit(videoSource)

    print("Showing Frame...")
    while True:
        print("thread count : ",threading.active_count())
        frame = getFrame.frame
        #frame = obd.predictYolo(frame)
        

        showFrame.frame = frame
 
        if getFrame.doVideo == False or showFrame.doVideo == False:
            getFrame.stop()
            showFrame.stop()
            sys.exit()

def working():
    cams=[0,1,2]
    for cam in cams:
        Process(target=main,args=(cam,)).start()

if __name__=="__main__":
    working()

下面是我的getFrame和showFrame类:

class getFrames():
    def __init__(self, 
                 videoSource:Union[int,str]=0):
        self.stream = self.videoInit(videoSource)
        self.hasFrame, self.frame = self.stream.read()
        self.doVideo = True

    def videoInit(self,
                  videoSource:Union[int,str]):
        try:
            cap = cv2.VideoCapture(videoSource)
        except Exception as e:
            raise Exception(f"Video source error: {e}")

        return cap

    def start(self):
        Thread(target=self.getFrames, args=()).start()
        return self

    def getFrames(self):
        while self.doVideo:
            if not self.hasFrame:
                self.stop()
            else:
                (self.hasFrame, self.frame) = self.stream.read()

    def stop(self):
        self.doVideo = False
        self.stream.release()

class showFrames():
    def __init__(self, 
                 frame:cv2=None):
        self.frame = frame
        self.doVideo = True

    def start(self):
        Thread(target=self.showFrame, args=()).start()
        return self

    def showFrame(self):
        while self.doVideo:
            cv2.imshow("Video", self.frame)
            if cv2.waitKey(1) == ord("q"):
                self.doVideo = False

    def stop(self):
        self.doVideo = False

最后是我的目标。预测:

 @jit(nopython=True, parallel=True) 
    def predictYolo(self,
                    frame:cv2) -> cv2:
        net = self.net

        height, width, channels = frame.shape
        
        blob = cv2.dnn.blobFromImage(frame, 1 / 255.0, (416, 416),swapRB=True, crop=False)       
        net.setInput(blob)
        outs = net.forward(self.output_layers)
        
        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.8:
                    # 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)

        indexes = cv2.dnn.NMSBoxes(boxes, confidences, 0.7, 0.4)
        font = cv2.FONT_HERSHEY_PLAIN
        classes=self.classes
        colors = np.random.uniform(130, 255, size=(len(classes), 3))
        for i in range(len(boxes)):
            if i in indexes:
                x, y, w, h = boxes[i]
                label = str(classes[class_ids[i]])
                if label=="With Helmet":
                    label="Helmet"
                    color=(0,255,0)
                elif label=="Without Helmet":
                    label="Violation"
                    color=(0,0,255)
              
                self.createBB(x,y,w,h,frame=frame,label=label,color=color)
        self.frame=frame
        #print("sending finish processed frame ...")
        return frame

程序中是否存在导致代码始终试图占用最大cpu资源的错误?谢谢