Skip to content Skip to sidebar Skip to footer

Multi-threading, What Is Wrong With My Code

I was trying to make faster my frames in opencv, it was so slow using it normal, so I decided to ask it here Make faster videocapture opencv the answer was to use multi threading t

Solution 1:

Your VideoStream class's init looks ok, but I think you might have better luck creating a cv2 VideoCapture object in the init as well:

self.stream = cv2.VideoCapture(0)

I'm not really as familiar with webcam.set() but if you want to incorporate that, I'm sure you can.

Here you have grabbed the initial frames:

self.status, self.frame = webcam.read()

(Or using the new self.stream variable):

self.status, self.frame = self.stream.read()

Yet this will only grab a frame when it's initialized, not in a loop. To achieve a loop, you have to make a few more class methods. One will be for continuously getting frames (I added a self.stopped attribute, although it's not in your code. It might be a good idea to have a True/False stop flag):

defread_stream(self):
    whilenotself.stopped:
        (self.grabbed, self.frame) = self.stream.read()

Then if you want to use multithreading, you can make a thread pointing to the read_stream method:

defstart(self):
    Thread(target=self.read_stream, args=()).start()
    returnself

You will have to call the start() method on the VideoStream before you start your CV2 imshow() loop.

video_stream = VideoStream().start().  #<------Here--------while webcam.isOpened():
    
    face_detection()

    # display output
    cv2.imshow("Gender Detection", gender_detection.frame)

    # press "Q" to stopif cv2.waitKey(1) & 0xFF == ord('q'):
        break

Hopefully this helps getting the CV2 display to show. Whether your GFR class or face detection is grabbing the right frames from the VideoStream class... that's something else, and I can't debug all that code.

Post a Comment for "Multi-threading, What Is Wrong With My Code"