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.