Prashant Gupta
Prashant Gupta

Reputation: 439

Multi-threading on python for running 2 inter-related threads simultaneously (or may be background processing)

I want VideoCapture function from opencv to work smoothly while processing frames from it in background. As processing requires 3-4 seconds so at that time capturing video hangs. Hence, I need to run 2 threads, i.e., one capturing video and other processing its output and printing on screen. My code till now:

age = None
while True:
    ret, frame = cam.read()
    if ret == True:
        # do some processing (3-4 seconds)
        age = process(frame)

        fr = update_age(frame, age)
        cv2.imshow('hello', fr)
        if cv2.waitKey(1) == 27:
            break
    else:
        print "error"
        break
cv2.destroyAllWindows()

Hence, I need a way so that my 3rd line don't have to wait 3-4 seconds to update its frame, while processing frames and printing its output runs in background.

More Clarifications(mentioned in comments also):

Upvotes: 1

Views: 586

Answers (1)

Stephanie Marker
Stephanie Marker

Reputation: 116

Here's one example with multiprocessing where you would capture frames and process them later:

from multiprocessing import Process
import time

frame_data = 0

def capture_video():
    print('recording...')
    return frame_data

def process_frame(frame_data):
    time.sleep(3)
    print(frame_data)
    return frame_data

if __name__ == '__main__':
    while True:
        data = capture_video()
        p = Process(target=process_frame, args=(frame_data,))
        p.start()
        time.sleep(0.1) 
        frame_data = frame_data + 1

Example Output (removed a few initial recording... printouts for conciseness):

recording...
recording...
recording...
recording...
recording...
recording...
0
recording...
1
recording...
2
recording...
3
recording...
4
recording...

Upvotes: 0

Related Questions