user6906524
user6906524

Reputation:

How to do real-time face detection, opencv, python3, raspberrypi 3

I am trying to create a small program for personal use with the picamera and rpi3. I have been trying for a while to implement real-time face detection using opencv. It never works. The error code I get is "error: (-215) scn == 3 || scn == 4 in function cvtColor"

The code I am trying to use is:

import numpy as np
import cv2
cam = cv2.VideoCapture(0)
name = 'detect'
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE)
while True:
    s, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    cv2.imshow(name, img)    
    k = cv2.waitKey(0)
    if k == 27:
        cv2.destroyWindow("Detect")
        break

Disclaimer, the code I have posted here is not mine. I intended to copy-paste-edit the code for PERSONAL use. I do not claim to have created it, I just need it to work

Many thanks in advance

Upvotes: 0

Views: 525

Answers (1)

user6906524
user6906524

Reputation:

I have found a solution. Instead of using the code I posted above, I have stolen some new code and edited it to my liking. For some reason, it can only work when triggered from the terminal but that is acceptable.

The command needed (on linux) is : cd (path_to_script) && python3 (script_name) --picamera 1

Thanks to @beaker for helping me

from imutils.video import VideoStream
from imutils import face_utils
import datetime
import argparse
import imutils
import time
import dlib
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-r", "--picamera", type=int, default=-1,
    help="whether or not the Raspberry Pi camera should be used")
args = vars(ap.parse_args())
print("[INFO] camera sensor warming up...")
vs = VideoStream(usePiCamera=args["picamera"] > 0).start()
time.sleep(2.0)
faceCascade = cv2.CascadeClassifier('/home/pi/Documents/Python Projects/Camera/haarcascade_frontalface_default.xml')
while True:
    frame = vs.read()
    frame = imutils.resize(frame, width=400)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(30, 30),
        flags = cv2.CASCADE_SCALE_IMAGE)
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 10)
    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break
cv2.destroyAllWindows()
vs.stop()

Disclaimer, the code I have posted here is not mine. I intended to copy-paste-edit the code for PERSONAL use. I do not claim to have created it

Upvotes: 0

Related Questions