gapansi99
gapansi99

Reputation: 357

Keep streaming video while performing function in OpenCV?

I am pretty new to OpenCv in python and had a question.

Basically, I found a code that detects faces from your webcam and whenever a face is detected I would like to perform a specific task (let's call the task "my_function()").

import cv2, sys, numpy, os, time


def my_function():
    time.sleep(5)


haar_file = 'haarcascade_frontalface_default.xml'

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
webcam = cv2.VideoCapture(0)

while True:
    (_, im) = webcam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 4)
    for (x, y, w, h) in faces:
        cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
    
    if len(faces) != 0:
        my_function()


    cv2.imshow('OpenCV', im)
    key = cv2.waitKey(10)
    if key == 27:
        break

However, while "my_function" is running I would still like to have the video streaming from my webcam. As of now when a face is detected the webcam freezes for 5 seconds and then the stream continues until a new face is detected. I would like the webcam to continue streaming in the open window without waiting for "my_function" to be completed.

Thanks in advance!

Upvotes: 0

Views: 798

Answers (1)

unityJarvis
unityJarvis

Reputation: 369

The threading module could be used here. Calling my_function in a different thread could avoid the freezing. For example

from threading import Thread
import cv2, sys, numpy, os, time


def my_function():
    time.sleep(5)


haar_file = 'haarcascade_frontalface_default.xml'

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
webcam = cv2.VideoCapture(0)

while True:
    (_, im) = webcam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 4)
    for (x, y, w, h) in faces:
        cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)

    t1 = Thread(target = my_function, args=(),)  # Create thread

    if len(faces) != 0:
        t1.start()  # start the thread, i.e., execute the function


    cv2.imshow('OpenCV', im)
    key = cv2.waitKey(10)
    if key == 27:
        break

Note: The freezing happens due to the Global Interpreter Lock in Python and this is a very basic solution for the same. Read more about GIL and multiprocessing here: What Is the Python Global Interpreter Lock (GIL)? – Real Python

Upvotes: 3

Related Questions