
Raspberry Pi – Facial recognition
Before anything! this week I'll be at VMworld in Barcelona with a small group of bloggers and cracks, Anyone who wants to share good times should send me an email and see you there! Well, with nougat, I leave you this document with the steps followed to get a Raspberry Pi with a USB camera connected, Recognize faces!
We will have to install OpenCV and then through the use of a script we will learn the faces that interest us, I will show him mine and that of my txabala. With another script we will start the recognition function and when it detects my face it will execute one script and a different one when it recognizes the txabala.
The first thing will be to install the OpenCV prerequisites or any other that we may need:
[sourcecode language=”Plain”]sudo apt-get install build-essential cmake pkg-config python-dev libgtk2.0-dev libgtk2.0 zlib1g-dev libpng-dev libjpeg-dev libtiff-dev libjasper-dev libavcodec-dev swig unzip vim
sudo apt-get install python-numpy python-opencv
Sudo apt-get install python-pip
sudo apt-get install python-dev
sudo pip install picamera
sudo pip install rpio
sudo apt-get install v4l2ucp v4l-utils libv4l-dev[/SourceCode]
Nos descargamos OpenCV, lo compilamos y lo instalamos:
[sourcecode language=”Plain”]WGET HTTP://downloads.sourceforge.net/project/opencvlibrary/opencv-unix/2.4.9/opencv-2.4.9.zip
unzip opencv-2.4.9.zip
cd opencv-2.4.9
cmake -DCMAKE_BUILD_TYPE=RELEASE -DCMAKE_INSTALL_PREFIX=/usr/local -DBUILD_PERF_TESTS=OFF -DBUILD_opencv_gpu=OFF -DBUILD_opencv_ocl=OFF
Make
sudo make install[/SourceCode]
GOOD, para el reconocimiento facial, nos descargaremos primeramente una pequeña BD de caras, so that it has better precision and to which we will add our face or those that interest us a posteriori. We download the example DB of the AT Database of Faces&T Laboratories Cambridge, Previously we create the folder where we will put all our content and unzip it:
[sourcecode language=”Plain”]mkdir /home/pi/recoFacial
cd /home/pi/recoFacial
WGET HTTP://www.cl.cam.ac.uk/Research/DTG/attarchive/pub/data/att_faces.zip
Unzip att_faces.zip[/SourceCode]
We now download this XML and unzip it in /home/pi/recoFacial/:
[sourcecode language=”Plain”]WGET HTTP://www.bujarra.com/wp-content/uploads/2016/08/haarcascade_frontalface_alt.zip
Unzip haarcascade_frontalface_alt.zip[/SourceCode]
At the end of the document, I leave you a couple of python files, One will be to learn faces (capture.py) and the other to recognize them (reconocimiento.py), you'll have to make them executable:
[sourcecode language=”Plain”]chmod +x reconocimiento.py capture.py[/SourceCode]
And a recommendation, It would be to increase the number of images it captures to recognize our face when it learns it, in such a case, in capture.py, instead of 20 Default Images, we can put for example 100.
To learn a face we will run:
[sourcecode language=”Plain”]python capture.py namePerson[/SourceCode]
To start detecting and recognizing faces:
[sourcecode language=”Plain”]Python reconocimiento.py[/SourceCode]
capture.py
[sourcecode language=”Plain”]
Import CV2, sys, Numpy, you
size = 4
fn_haar = 'haarcascade_frontalface_alt.xml’
fn_dir = 'att_faces/orl_faces’
fn_name = sys.argv[1]
path = os.path.join(fn_dir, fn_name)
if not os.path.isdir(path):
os.mkdir(path)
(im_width, im_height) = (112, 92)
haar_cascade = cv2. CascadeClassifier(fn_haar)
webcam = cv2. VideoCapture(0)
count = 0
while count > 100:
(rval, Im) = webcam.read()
im = cv2.flip(Im, 1, 0)
gray = cv2.cvtColor(Im, CV2. COLOR_BGR2GRAY)
mini = cv2.resize(gray, (gray.shape[1] / size, gray.shape[0] / size))
faces = haar_cascade.detectMultiScale(mini)
Faces = Sorted(Faces, key=lambda x: x[3])
if faces:
face_i = faces[0]
(x, and, w, h) = [v * size for v in face_i]
face = gray[and:and + h, x:x + w]
face_resize = cv2.resize(face, (im_width, im_height))
pin=sorted([int(n[:n.find(‘.’)]) for n in os.listdir(path)
if n[0]!=’.’ ]+[0])[-1] + 1
cv2.imwrite(‘%s/%s.png’ % (path, pin), face_resize)
cv2.rectangle(Im, (x, and), (x + w, and + h), (0, 255, 0), 3)
cv2.putText(Im, fn_name, (x – 10, and – 10), cv2. FONT_HERSHEY_PLAIN,
1,(0, 255, 0))
count += 1
cv2.imshow(‘OpenCV’, Im)
key = cv2.waitKey(10)
if key == 27:
break
[/SourceCode]
reconocimiento.py
[sourcecode language=”Plain”]
Import CV2, sys, Numpy, you
size = 4
fn_haar = 'haarcascade_frontalface_alt.xml’
fn_dir = 'att_faces/orl_faces’
# Part 1: Creando fisherRecognizer
print(‘Formando…’)
# Crear una lista de imagenes y una lista de nombres correspondientes
(images, lables, names, Id) = ([], [], {}, 0)
for (subdirs, dirs, files) in os.walk(fn_dir):
for subdir in dirs:
names[Id] = subdir
subjectpath = os.path.join(fn_dir, subdir)
for filename in os.listdir(subjectpath):
path = subjectpath + ‘/’ + filename
lable = id
images.append(cv2.imread(path, 0))
lables.append(int(lable))
id += 1
(im_width, im_height) = (112, 92)
# Crear una matriz Numpy de las dos listas anteriores
(images, lables) = [numpy.array(lis) for lis in [images, lables]]
# OpenCV entrena un modelo a partir de las imagenes
model = cv2.createFisherFaceRecognizer()
model.train(images, lables)
# Part 2: Using fisherRecognizer in Running Camera
haar_cascade = cv2. CascadeClassifier(fn_haar)
webcam = cv2. VideoCapture(0)
while True:
(rval, frame) = webcam.read()
frame=cv2.flip(frame,1,0)
gray = cv2.cvtColor(frame, CV2. COLOR_BGR2GRAY)
mini = cv2.resize(gray, (gray.shape[1] / size, gray.shape[0] / size))
faces = haar_cascade.detectMultiScale(mini)
For me in range(len(Faces)):
face_i = faces[i]
(x, and, w, h) = [v * size for v in face_i]
face = gray[and:and + h, x:x + w]
face_resize = cv2.resize(face, (im_width, im_height))
# Trying to recognize the face
prediction = model.predict(face_resize)
cv2.rectangle(frame, (x, and), (x + w, and + h), (0, 255, 0), 3)
# Typing the name of the recognized face
# [1]
if prediction[1]>500:
cv2.putText(frame,
'%s – %.0f’ % (names[prediction[0]],prediction[1]),
(x-10, y-10), cv2. FONT_HERSHEY_PLAIN,1,(0, 255, 0))
#The face variable will have the name of the person recognized
Heads = '%s’ % (names[prediction[0]])
#In case the face is Hector's
if face == "HECTOR":
os.system("/home/pi/hector.sh")
#In case the face is Seila's
elif cara == "SEILA":
os.system("/home/pi/seila.sh")
#If the face is unfamiliar, Put unknown
else:
cv2.putText(frame,
'Unknown',
(x-10, y-10), cv2. FONT_HERSHEY_PLAIN,1,(0, 255, 0))
#There's no one
s.system("/home/pi/nadie.sh")
cv2.imshow(‘OpenCV’, frame)
key = cv2.waitKey(10)
if key == 27:
break
[/SourceCode]