opencv + pi camera running slow

asked 2016-11-24 12:51:44 -0600

dnclem gravatar image

Hi there.

I'm using the Raspberry Pi camera + openCV on the Pi to detect a human. It works completely fine, only problem being it runs really slow. I know the Pi doesn't have an amazing processor, and that this sort of image processing requires a lot of power, but my camera shows one frame every second or two. This is the code I'm using:

import numpy as np
import cv2
import time
import imutils
from imutils.video.pivideostream import PiVideoStream
from imutils.video import FPS
from picamera.array import PiRGBArray
from picamera import PiCamera

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
if face_cascade.empty(): raise Exception("unable to load face cascade, check if path is correct")

eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
if eye_cascade.empty(): raise Exception("unable to load eye cascade, check if path is correct")

#camera = PiCamera()
#camera.resolution = (320, 240)
#camera.framerate = 32
#rawCapture = PiRGBArray(camera, size = (320, 240))
#stream = camera.capture_continuous(rawCapture, format = "bgr", use_video_port = True)
#video = PiVideoStream().start()


video = cv2.VideoCapture(0)


while (video.isOpened()): #while the vid's on..
    #cv2.waitKey()
    ret, frame = video.read() #read
    if frame is not None:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x,y,w,h) in faces:
            cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]
            eyes = eye_cascade.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
        cv2.imshow('Video', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

Is there a way I could increase the frame rate? I tried adding time.sleep() in the loop to process frames every x seconds or so but that didn't make a difference. Lowering the framerate to 320x240 makes a small improvement, but I'm wondering if there are other ways to speed this up as well.

Thanks in advance.

edit retag flag offensive close merge delete