Wednesday, February 2, 2022

[SOLVED] The Picamera does not work in face recognition using Raspberry Pi

Issue

I am a newbie with python and R-Pi. So After watching Adrian's tutorial, I want to get facial recognition to work. (href="https://www.pyimagesearch.com/2018/06/11/how-to-build-a-custom-face-recognition-dataset/" rel="nofollow noreferrer">https://www.pyimagesearch.com/2018/06/11/how-to-build-a-custom-face-recognition-dataset/)

My picamera normally works fine, but when following the post above, my picamera doesn't work.

Here's my source code:

from imutils.video import VideoStream
import argparse
import imutils
import time
import cv2
import os

ap = argparse.ArgumentParser()
ap.add_argument("-c", "--cascade", required=True,
    help = "path to where the face cascade resides")
ap.add_argument("-o", "--output", required=True,
    help="path to output directory")
args = vars(ap.parse_args())

detector = cv2.CascadeClassifier(args["cascade"])
print("[INFO] starting video stream...")
#vs = VideoStream(src=0).start()
 vs = VideoStream(usePiCamera=True).start()
time.sleep(2.0)
total = 0

while True:

    frame = vs.read()
    orig = frame.copy()
    frame = imutils.resize(frame, width=400)

    rects = detector.detectMultiScale(
        cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), scaleFactor=1.1, 
        minNeighbors=5, minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF
 
    if key == ord("k"):
        p = os.path.sep.join([args["output"], "{}.png".format(
            str(total).zfill(5))])
        cv2.imwrite(p, orig)
        total += 1
    elif key == ord("q"):
        break

print("[INFO] {} face images stored".format(total))
print("[INFO] cleaning up...")
cv2.destroyAllWindows()
vs.stop()

When I run this code,

[INFO] starting video stream...

appears but the camera does not appear on the Raspberry Pi; and, when I face the camera,

[INFO] {} face images stored 
[INFO] cleaning up...

appears.


Solution

Could you try this.

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


Answered By - JB_DELR
Answer Checked By - Dawn Plyler (WPSolving Volunteer)