Optical sensor

A camera can be used as an optical sensor to capture what's happening in a certain area. Every camera has different features. You should choose the appropriate camera for your use case. By adding artificial intelligence (AI) program with your camera, you can use it to detect human presence.

The Raspberry Pi Foundation provides the official camera for the Raspberry Pi. Currently, the recommended camera is the camera module version 2. You can read about and buy it at https://www.raspberrypi.org/products/camera-module-v2/. The Raspberry Pi foundation also has the Pi Camera Noire V2. This camera can work in low light. You can find this product at https://www.raspberrypi.org/products/pi-noir-camera-v2/. You can see it here:

A simple method to detect human presence is to use a face detection algorithm. When we connect a camera to an ad monitor, we can assume that if people are watching the monitor, their faces will be seen.

We can use OpenCV to implement face detection. For instance, we can detect a face in a picture file using Haar Cascade. You can use this program:

import numpy as np 
import cv2 
 
 
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') 
 
img = cv2.imread('IMG_FACE.JPG') 
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
 
faces = face_cascade.detectMultiScale(gray, 1.3, 5) 
for (x, y, w, h) in faces: 
    img = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 255), 2) 
 
print "Number of faces detected: " + str(faces.shape[0]) 
 
cv2.imshow('img', img) 
cv2.waitKey(0) 
cv2.destroyAllWindows() 

You should change the image file with your test picture file. Save this program as ch04_faces.py.

Now you can run the program on a Terminal. Type this command:

    $ python ch04_faces.py

You can see rectangles on the picture if there is a human face. Take a look at the test picture here:

In a terminal, the program will display a message that shows the number of detected faces. You can see it here:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.35.158