限制python和opencv上的视频捕获帧率

Kur*_*lar 2 python linux video opencv video-capture

我正在尝试从 ip 摄像头捕获视频并将其保存为 avi 视频文件。同时脚本将包含人脸的帧保存为 jpeg 文件。当脚本执行这些工作时,cpu 使用率约为 100%。因此,我只想在面部检测上限制帧速率。

我的代码是:

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
now = datetime.datetime.now()
strtime = str(now)
cap = cv2.VideoCapture('rtsp://root:root@10.10.10.56: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)
Run Code Online (Sandbox Code Playgroud)

我在许多不同的地方尝试过 cv2.VideoCapture.set(cv2.CAP_PROP_FPS,2) 但它没有用。有什么方法可以限制视频捕获fps吗?

Kur*_*lar 5

经过多次尝试,我找到了适合我需求的解决方案。我计算帧数,并每 10 帧进行一次面部检测的 for 循环。当我将相机设置为流式传输 10 fps 视频时,这应该意味着面部检测流为 1 fps。

编码解决方案:

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)
Run Code Online (Sandbox Code Playgroud)