Ouverture de la maison (Servomoteur)

Si la "bonne" personne est détecté, on commande l'ouverture de sa maison.

On va se servir d'un servomoteur pour notre maquette, représentant le déverrouillage de la maison si la personne est reconnue devant sa maison.

Schéma de connexion

Le Servo moteur possède 3 fils :

  • Le fil rouge : +5V;

  • Le fil noir : GND, 0V;

  • Le fil blanc/jaune : fil de data, où les ordres circulent du Raspberry vers le Servo.

Pour alimenter le Servo, il est préférable d'utiliser une alimentation externe de 5V, surtout si l'alimentation de votre Raspberry délivre peu de courant.

Voici la description des broches du Raspberry Pi 3.

Exemple de code.

Tester ce code :

1
import RPi.GPIO as GPIO
2
import time
3
4
GPIO.setmode(GPIO.BCM)
5
GPIO.setup(17, GPIO.OUT)
6
GPIO.setwarnings(False)
7
8
ajoutAngle = 5
9
10
print("\n+----------/ ServoMoteur  Controlleur /----------+")
11
print("|                                                |")
12
print("| Le Servo doit etre branche au pin 11 / GPIO 17 |")
13
print("|                                                |")
14
print("+------------------------------------------------+\n")
15
16
print("Comment controler le Servo ?")
17
choix = int(input("1. Choisir un angle\n2. Faire tourner de 0 a 180\n"))
18
19
20
if (choix == 2) :
21
    nbrTour = int(input("Entrez le nombre d'aller-retour que fera le Servo :\n"))
22
23
    pwm=GPIO.PWM(17,100)
24
    pwm.start(5)
25
26
    angle1 = 0
27
    duty1 = float(angle1)/10 + ajoutAngle
28
29
    angle2=180
30
    duty2= float(angle2)/10 + ajoutAngle
31
32
    i = 0
33
34
    while i <= nbrTour:
35
         pwm.ChangeDutyCycle(duty1)
36
         time.sleep(0.8)
37
         pwm.ChangeDutyCycle(duty2)
38
         time.sleep(0.8)
39
         i = i+1
40
    GPIO.cleanup()
41
42
if (choix == 1) :
43
    angle = float(input("Entrez l'angle souhaite :\n"))
44
    duree = int(input("Entrez la duree durant laquelle le Servo devra tenir sa position : ( en secondes )\n"))
45
46
    pwm=GPIO.PWM(17,100)
47
    pwm.start(5)
48
49
    angleChoisi = angle/10 + ajoutAngle
50
    pwm.ChangeDutyCycle(angleChoisi)
51
    time.sleep(duree)
52
    GPIO.cleanup()

Question

Réaliser le montage c-dessus.

Question

Combiner les 2 codes (reconnaissance faciale et servomoteur pour remplir l'objectif fixée.

Code de base de la reconnaissance faciale

1
# USAGE
2
# python pi_face_recognition.py --cascade haarcascade_frontalface_default.xml --encodings encodings.pickle
3
4
# import the necessary packages
5
from imutils.video import VideoStream
6
from imutils.video import FPS
7
import face_recognition
8
import argparse
9
import imutils
10
import pickle
11
import time
12
import cv2
13
14
# construct the argument parser and parse the arguments
15
ap = argparse.ArgumentParser()
16
ap.add_argument("-c", "--cascade", required=True,
17
	help = "path to where the face cascade resides")
18
ap.add_argument("-e", "--encodings", required=True,
19
	help="path to serialized db of facial encodings")
20
args = vars(ap.parse_args())
21
22
# load the known faces and embeddings along with OpenCV's Haar
23
# cascade for face detection
24
print("[INFO] loading encodings + face detector...")
25
data = pickle.loads(open(args["encodings"], "rb").read())
26
detector = cv2.CascadeClassifier(args["cascade"])
27
28
# initialize the video stream and allow the camera sensor to warm up
29
print("[INFO] starting video stream...")
30
vs = VideoStream(src=0).start()
31
# vs = VideoStream(usePiCamera=True).start()
32
time.sleep(2.0)
33
34
# start the FPS counter
35
fps = FPS().start()
36
37
# loop over frames from the video file stream
38
while True:
39
	# grab the frame from the threaded video stream and resize it
40
	# to 500px (to speedup processing)
41
	frame = vs.read()
42
	frame = imutils.resize(frame, width=500)
43
	
44
	# convert the input frame from (1) BGR to grayscale (for face
45
	# detection) and (2) from BGR to RGB (for face recognition)
46
	gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
47
	rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
48
49
	# detect faces in the grayscale frame
50
	rects = detector.detectMultiScale(gray, scaleFactor=1.1, 
51
		minNeighbors=5, minSize=(30, 30),
52
		flags=cv2.CASCADE_SCALE_IMAGE)
53
54
	# OpenCV returns bounding box coordinates in (x, y, w, h) order
55
	# but we need them in (top, right, bottom, left) order, so we
56
	# need to do a bit of reordering
57
	boxes = [(y, x + w, y + h, x) for (x, y, w, h) in rects]
58
59
	# compute the facial embeddings for each face bounding box
60
	encodings = face_recognition.face_encodings(rgb, boxes)
61
	names = []
62
63
	# loop over the facial embeddings
64
	for encoding in encodings:
65
		# attempt to match each face in the input image to our known
66
		# encodings
67
		matches = face_recognition.compare_faces(data["encodings"],
68
			encoding)
69
		name = "Unknown"
70
71
		# check to see if we have found a match
72
		if True in matches:
73
			# find the indexes of all matched faces then initialize a
74
			# dictionary to count the total number of times each face
75
			# was matched
76
			matchedIdxs = [i for (i, b) in enumerate(matches) if b]
77
			counts = {}
78
79
			# loop over the matched indexes and maintain a count for
80
			# each recognized face face
81
			for i in matchedIdxs:
82
				name = data["names"][i]
83
				counts[name] = counts.get(name, 0) + 1
84
85
			# determine the recognized face with the largest number
86
			# of votes (note: in the event of an unlikely tie Python
87
			# will select first entry in the dictionary)
88
			name = max(counts, key=counts.get)
89
		
90
		# update the list of names
91
		names.append(name)
92
93
	# loop over the recognized faces
94
	for ((top, right, bottom, left), name) in zip(boxes, names):
95
		# draw the predicted face name on the image
96
		cv2.rectangle(frame, (left, top), (right, bottom),
97
			(0, 255, 0), 2)
98
		y = top - 15 if top - 15 > 15 else top + 15
99
		cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
100
			0.75, (0, 255, 0), 2)
101
102
	# display the image to our screen
103
	cv2.imshow("Frame", frame)
104
	key = cv2.waitKey(1) & 0xFF
105
106
	# if the `q` key was pressed, break from the loop
107
	if key == ord("q"):
108
		break
109
110
	# update the FPS counter
111
	fps.update()
112
113
# stop the timer and display FPS information
114
fps.stop()
115
print("[INFO] elasped time: {:.2f}".format(fps.elapsed()))
116
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
117
118
# do a bit of cleanup
119
cv2.destroyAllWindows()
120
vs.stop()