I tried real-time face recognition with a webcam on Jetson Nano.
-How to install OpenCV -Easy-to-understand explanation about face recognition of OpenCV -How to get video with OpenCV
First, let's check how to get the image with the webcam. It was really easy.
camTest.py
import cv2
#Launch camera
capture = cv2.VideoCapture(0)
while(True):
#Get 1 frame image
ret, frame = capture.read()
#Display image in window
cv2.imshow("frame", frame)
#Stop when q is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#release
capture.release()
cv2.destroyAllWindows()
It stops when I press q
, but it doesn't work properly unless I press it with the focus on the window instead of the terminal.
When you install OpenCV, the file of the cascade classifier is included, so use it. (https://github.com/opencv/opencv/tree/master/data/haarcascades)
The procedure for face recognition is as follows
find_face.py
# -*- coding: utf-8 -*-
import time
import cv2
#Frame size (larger makes processing heavier)
FRAME_W = 320
FRAME_H = 240
#Cascade classifier for face detection (likely a file that summarizes features)
#I got an error when I tried to read something that was in another folder, so I copied it to the same folder
cascadeFilePath = './haarcascade_frontalface_default.xml'
cascade = cv2.CascadeClassifier(cascadeFilePath)
#Camera settings
cam = cv2.VideoCapture(0)
time.sleep(1) #Waiting for startup (for the time being)
cam.set(cv2.CAP_PROP_FPS, 60) #I don't know if it was 60
cam.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_W)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_H)
while(True):
#End with q
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#Image acquisition
ret, frame = cam.read()
#Convert to grayscale
gray_image = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
#Face recognition
facerect = cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=2, minSize=(30, 30))
#Was the face detected?
if len(facerect) > 0:
#Border color
line_color = (255, 102, 51)
#Text color
font_color = (255, 102, 51)
#Write a frame and FACE characters on the detected face
for (x, y, width, height) in facerect:
cv2.rectangle(frame, (x, y), (x + width, y + height), line_color, 2)
cv2.putText(frame, 'FACE', (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, font_color, 1, cv2.LINE_AA)
#Show in window
cv2.imshow('frame', frame)
#End processing
cam.release()
cv2.destroyAllWindows()
Recognized in real time!
Recommended Posts