2015-12-30 93 views
0

我试图从ip摄像头捕获视频并保存为avi视频文件。同时脚本将包含面部的帧保存为jpeg文件。虽然脚本正在做这些工作,但CPU使用率大约是100%。正因为如此,我想限制帧速率只在人脸检测。在python和opencv上限制视频捕获帧率

我的代码是:

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) 

我已经在许多不同的地方(2 cv2.CAP_PROP_FPS)试图cv2.VideoCapture.set,但没有奏效。有什么办法可以限制视频捕捉fps吗?

回答

2

经过多次尝试,我找到了适合我需求的解决方案。我计算帧数并为每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)