2

I am working on an image-processing project where I want pictures from 3 cameras to get the latest frame when a button is pressed and for that, I have used multiprocessing.process and multiprocessing.queue as shown in the code below. The required task is achieved but there are 2 problems right now:

1.cpu-100% in task manager(which slows down the program)

2.there is a workaround for cam.set(cv2.CAP_PROP_BUFFERSIZE, 0) in the code which is the main cause for 50% of cpu usage

actually I want a fast way to get frames so I have also tried multiprocessing.pipe instead of the queue but since it does not get the latest frame when button pressed for the second time so I had to use queu communication method. Any help regarding code would be much appreciated

def camera_func(queue,cam_indx):
    cam = cv2.VideoCapture(cam_indx,cv2.CAP_DSHOW)   #current camera
    cam.set(cv2.CAP_PROP_BUFFERSIZE, 0)
    if cam.isOpened(): # Check success if the object is created and opened                    
        while True:
            try:
                flag, frame=cam.read()
                if flag==0:
                    break 
                # used to remove buffer size problem because it gets next frame 
                # rather latest frame   
                if not queue.empty():
                    try:
                        queue.get_nowait()   # discard previous (unprocessed) frame
                    except Queue.Empty:
                        pass

                queue.put(frame,False)

            except:
                continue      
    else:               
        cam.open()        
        raise Exception("Could not open camera")

queues=[]
for pip in range(0,a_cams):
    queu = Queue(maxsize=1)
    queues.append(queu)

processes = [Process(target=camera_func, args=(queues[x],x)) for x in range(a_cams)]   # Setup a list of processes that we want to run
for p in processes:     
    p.start()   # Run processes

Update:

I have used threading as suggested by nathancy and now it is doing the same task without the workaround thanks to fps sync from here, and CPU usage is still 80% but this time there is 40-sec lag when starting the program which is too much.

4

2 回答 2

2

我有一个类似的问题。我发现这与我检查队列的方式直接相关。

我也有

if not queue.empty():
    try:
        r = queue.get()
        ...

将 cpu 负载降低到接近零的原因是删除了 .empty() 检查。.get() 调用会在继续之前自动等待队列中出现某些内容。

于 2020-11-25T20:05:43.293 回答
1

愿有人觉得它有用!

由于没有人回答我的问题,所以尽我所能尝试一切,我发现只有更改capture = cv2.VideoCapture(src)相机输入的线程版本中的行才能capture = cv2.VideoCapture(src,cv2.CAP_DSHOW)显着降低 CPU 使用率,而且开始时也没有延迟。

于 2019-12-16T00:10:29.200 回答