Face Detection On Pi Camera Image Using OpenCV Python3 on Raspberry Pi

Introduction

Image Processing is often referred to as ‘Digital Image Processing’ and the domain where it is commonly used is ‘Computer Vision’. Make no mistake – we’ll discuss these two terms and how they relate. Both the Image Processing algorithm and the Computer Vision (CV) algorithm take pictures as input; however, in image processing, the output is also an image, whereas in the computer vision output there can be some features/information about the image. There’s one that we use the most, the Open CV library. In this video, we will use Haar Cascade to detect faces on the image captured by pi camera.

Video

This video shows how get a face detection on an pi camera image using OpenCV Python3 on Raspberry Pi.

Hardware Preparation

This is the list of items used in the video.

OR

OR

Sample Code

This is the sample code for this project.

import io
import picamera
import cv2
import numpy
#Create a memory stream so photos doesn't need to be saved in a file
stream = io.BytesIO()
#Get the picture (low resolution, so it should be quite fast)
#Here you can also specify other parameters (e.g.:rotate the image)
with picamera.PiCamera() as camera:
camera.resolution = (320, 240)
camera.capture(stream, format='jpeg')
#Convert the picture into a numpy array
buff = numpy.frombuffer(stream.getvalue(), dtype=numpy.uint8)
#Now creates an OpenCV image
image = cv2.imdecode(buff, 1)
#https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml
#Load a cascade file for detecting faces
face_cascade = cv2.CascadeClassifier('/home/pi/Face Recognition/haarcascade_frontalface_default.xml')
#Convert to grayscale
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
#Look for faces in the image using the loaded cascade file
faces = face_cascade.detectMultiScale(gray, 1.1, 5)
print ("Found {}" + str(len(faces)) + " face(s)")
#Draw a rectangle around every found face
for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,0),4)
#Save the result image
cv2.imwrite('result.jpg',image)

view raw
face_recognition.py
hosted with ❤ by GitHub

Thank You

References:

Thanks for reading this tutorial. If you have any technical inquiries, please post at Cytron Technical Forum.

Please be reminded, this tutorial is prepared for you to try and learn.
You are encouraged to improve the code for better application.

Leave a Comment

Your email address will not be published.

Share this Tutorial

Share on facebook
Share on whatsapp
Share on email
Share on print
Share on twitter
Share on pinterest
Share on facebook
Share on whatsapp
Share on email
Share on print
Share on twitter
Share on pinterest

Latest Tutorial

Send Data to Firebase Using Arduino Uno WiFi Rev2
Simple Alarm System Using Maker Nano
Program Cucumber ESP32-S2 Using CircuitPython
Face Recognition Using OpenCV on Raspberry Pi 400
Turned Your Tablet as a Display for the Raspberry Pi 400
Scroll to Top