Kursat Serolar
Kursat Serolar

Reputation: 147

Limiting video capture frame rate on python and opencv

I am trying to capture video from ip camera and save as avi video file. At the same time script is saving the frames which contains faces as jpeg file. While script is doing these jobs cpu usage is about 100%. Because of this i want to limit frame rate only on face detection.

My code is:

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
now = datetime.datetime.now()
strtime = str(now)
cap = cv2.VideoCapture('rtsp://root:[email protected]:554/stream/profile1=r')




fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('1/video/%s.avi' % strtime,fourcc, 10.0 , (960,540))

if cap.isOpened():


    while(True):
        if cap.set(cv2.CAP_PROP_FPS,4):

            try:


                ret, frame = cap.read()

                if ret==True:


                    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
                    out.write(frame)

                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        break
                    faces = face_cascade.detectMultiScale(gray,
                                                          scaleFactor=1.5,
                                                          minNeighbors=6,
                                                          minSize=(30,30))
                    for (x,y,w,h) in faces:
                        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),
                        cv2.imwrite('1/frames/%sf%s.jpg'%(now,str(cap.get(cv2.CAP_PROP_POS_FRAMES))), frame)


                    cv2.imshow('frame', frame)


            except KeyboardInterrupt:
                cap.release()
                out.release()
                cv2.destroyAllWindows()
                sys.exit(0)
                pass

else:
    print "Unable to connect"


cap.release()
out.release()
cv2.destroyAllWindows()
sys.exit(0)

I have tried cv2.VideoCapture.set(cv2.CAP_PROP_FPS,2) in many different places but it didn't work. Is there any way to limit video capture fps?

Upvotes: 2

Views: 7087

Answers (1)

Kursat Serolar
Kursat Serolar

Reputation: 147

After many tries I found a solution that suits my needs. I counted frames and made the for loop for face detection work every 10 frames. As I set my camera to stream 10 fps video this should mean face detection stream is 1 fps.

The coded solution:

if int(cap.get(cv2.CAP_PROP_POS_FRAMES)) % 10 == 0: 
    faces = face_cascade.detectMultiScale(gray,
                                          scaleFactor=1.5,
                                          minNeighbors=5,
                                          minSize=(30, 30))
    for (x, y, w, h) in faces:
         cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0))
         cv2.imwrite('1/frames/%sf%s.jpg'%(now, str(cap.get(cv2.CAP_PROP_POS_FRAMES))), frame)

Upvotes: 5

Related Questions