-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfinalcode.py
More file actions
479 lines (365 loc) · 14.2 KB
/
finalcode.py
File metadata and controls
479 lines (365 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
"""
Course: EECS 452
Project: Cop Dog
Team Members: Rahul Hingorani
Julia Kerst
Angela Brown
Saud Alrufaydah
Project Description:
"""
# Import modules
import numpy as np
import cv2
import time
import pygame
from random import randint
import wiringpi
import io
import traceback
import RPi.GPIO as GPIO
# Initialize global dictionary to hold player_id:player_name pairs
playerIDName = {}
# Initialize recognizer
recognizer = cv2.face.createLBPHFaceRecognizer()
# Set up GPIO
#follow board numbering system for pins
GPIO.setmode(GPIO.BOARD)
#set as input and pull down
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
"""
Define Robot Control State Machine
States:
1: robotForward
2: robotBackward
3: robotStop
4: robotRecord
5: robotSeek
"""
def robotForward():
forwardbuf = bytes([1,1,0])
retlen, retdata = wiringpi.wiringPiSPIDataRW(0, forwardbuf)
def robotBackward():
backbuf = bytes([2,2,0])
retlen, retdata = wiringpi.wiringPiSPIDataRW(0, backbuf)
def robotStop():
stopbuf = bytes([3,3,0])
retlen, retdata = wiringpi.wiringPiSPIDataRW(0, stopbuf)
def robotRecord(playerID):
recordbuf = bytes([4,playerID,0])
retlen, retdata = wiringpi.wiringPiSPIDataRW(0, recordbuf)
def robotSeek(numPlayers, criminalID):
seekbuf = bytes([5,criminalID,0])
retlen, retdata = wiringpi.wiringPiSPIDataRW(0, seekbuf)
def robotSeekOther(numPlayers, criminalID):
print('ENTERED')
# Start backwards movement
robotBackward()
time.sleep(0.05)
cam = cv2.VideoCapture(0)
# Initialize detector
detector = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/'
'haarcascades/haarcascade_frontalface_alt.xml')
detector2 = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/'
'haarcascades/haarcascade_frontalface_default.xml')
# Found face in previous frame
prevFrameFace = False
# Record ROI
ROI = -1
suspectID = numPlayers
foundFace = False
while suspectID >= criminalID:
# Get frame
ret,img = cam.read()
# Convert to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Decision #1: Check if previous frame had a face
if prevFrameFace:
# Detect faces sized +/-20% off biggest face in previous search
minSize = (int(ROI*8/10), int(ROI*8/10))
maxSize = (int(ROI*12/10), int(ROI*12/10))
else:
# Minimum face size is 1/5th of screen width
# Maximum face size is 2/3rds of screen width
hImg, wImg = gray.shape[:2]
minSize = (int(hImg/5),int(hImg/5))
maxSize = (int(hImg*2/3),int(hImg*2/3))
faces = detector.detectMultiScale(gray, 1.3, 3, 0, minSize, maxSize)
# If no face found, try different classifier
if len(faces) == 0:
faces = detector2.detectMultiScale(gray, 1.3, 3, 0, minSize, maxSize)
# If it still didn't work, no face
if len(faces) == 0:
prevFrameFace = False
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),2)
prevFrameFace = True
ROI = w
face_centered = checkFaceCentered(x,w,wImg)
if face_centered:
foundFace = True
if foundFace:
suspectID -= 1
foundFace = False
time.sleep(4)
# Stop when criminal is found
robotStop()
def predictSuspect(suspectID, criminal):
# Initialize camera
cam = cv2.VideoCapture(0)
# Initialize detector
detector = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/'
'haarcascades/haarcascade_frontalface_alt.xml')
detector2 = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/'
'haarcascades/haarcascade_frontalface_default.xml')
# Found face in previous frame
prevFrameFace = False
# Record ROI
ROI = -1
numImages = 0
predictions = []
confidences = []
while numImages <= 100:
# Get frame
ret,img = cam.read()
# Convert to gray scale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Decision #1: Check if previous frame had a face
if prevFrameFace:
# Detect faces sized +/-20% off biggest face in previous search
minSize = (int(ROI*8/10), int(ROI*8/10))
maxSize = (int(ROI*12/10), int(ROI*12/10))
else:
# Minimum face size is 1/5th of screen width
# Maximum face size is 2/3rds of screen width
hImg, wImg = gray.shape[:2]
minSize = (int(hImg/5),int(hImg/5))
maxSize = (int(hImg*2/3),int(hImg*2/3))
faces = detector.detectMultiScale(gray, 1.3, 3, 0, minSize, maxSize)
# If no face found, try different classifier
if len(faces) == 0:
faces = detector2.detectMultiScale(gray, 1.3, 3, 0, minSize, maxSize)
# If it still didn't work, no face
if len(faces) == 0:
prevFrameFace = False
printString = ""
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),4)
face = cv2.resize(gray[y:y+h, x:x+w], (150, 150))
prevFrameFace = True
ROI = w
face_centered = checkFaceCentered(x,w,wImg)
if face_centered:
# Stop when face is centered for the first time
if numImages == 0:
robotStop()
time.sleep(0.1)
robotRecord(suspectID)
# Make prediction
prediction,confidence = recognizer.predict(face)
predictions.append(prediction)
confidences.append(confidence)
if prediction == criminal:
color = (0,0,255)
for (x,y,w,h) in faces:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),4)
else:
color = (0,255,0)
print("Prediction: {}, Confidence: {}".format(playerIDName[prediction],confidence))
printString = '{} - {}'.format(playerIDName[prediction],confidence)
numImages += 1
cv2.putText(img,printString, (int(x+w*3/4),int(y-10)), cv2.FONT_HERSHEY_SIMPLEX, 1, color)
cv2.imshow('frame',img)
cv2.moveWindow('frame', 0, 0)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Majority pick vote
# Find the indices of the 100 lowest confidence values (most certain)
idx = np.argpartition(np.array(confidences),50)[:50]
topPredictions = [predictions[i] for i in idx]
lowestConfidences = [confidences[i] for i in idx]
predictedPlayer = max(set(predictions), key=predictions.count)
meanConfidence = np.mean(lowestConfidences)
cam.release()
cv2.destroyAllWindows()
return predictedPlayer, meanConfidence
def checkFaceCentered(xface, wface, w):
threshold = 60
xcenter = xface + wface//2
return ((xcenter < (w//2 + threshold)) and (xcenter > (w//2 - threshold)))
def scanSuspects(numPlayers, criminal):
predictions = []
confidences = []
for suspectID in range(1,numPlayers+1):
# Start moving robot
robotForward()
if suspectID > 1:
time.sleep(4)
prediction, meanConfidence = predictSuspect(suspectID, criminal)
predictions.append(prediction)
confidences.append(meanConfidence)
print("\nFinal Prediction: {}, Final Confidence: {}".format(playerIDName[prediction],meanConfidence))
# Make sure robot stopped
#robotStop()
return predictions, confidences
"""
Given an image, try to extract the face region of the image using
two different Haar Cascade Classifiers. If no face detected, return None.
Parameters: img
Returns: detectedFace - cropped image of just face region
"""
def getFace(img):
# Initialize classifiers - found to be best classifiers through testing
detector = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/'
'haarcascades/haarcascade_frontalface_alt.xml')
detector2 = cv2.CascadeClassifier('/home/pi/Downloads/opencv/data/'
'haarcascades/haarcascade_frontalface_default.xml')
# Convert to gray scale
grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Minimum face size is 1/5th of screen width
# Maximum face size is 2/3rds of screen width
h, w = grayImg.shape[:2]
minSize = (int(h/5),int(h/5))
maxSize = (int(h*2/3),int(h*2/3))
# Try first cascade classifier detection
faces = detector.detectMultiScale(grayImg, 1.3, 3, 0, minSize, maxSize)
# Try again with different classifier
if len(faces) != 1:
faces = detector2.detectMultiScale(grayImg, 1.3, 3, 0, minSize, maxSize)
# If it still didn't work, quit
if len(faces) != 1:
return None
for x,y,w,h, in faces:
detectedFace = grayImg[y:y+h, x:x+w]
# Need to set all faces to be same size for recognition
detectedFace = cv2.resize(detectedFace, (150, 150))
return detectedFace
"""
Takes a photo and tries to detect a face. If a face was detected,
the image is added to the training set, otherwise keep trying.
Parameters: None
Returns: faceImages - list of face images
"""
def takeMugshots():
numImages = 50
faceImages = []
# Initialize camera
cam = cv2.VideoCapture(0)
# Loop that goes on until we find enough face photos
findingFaces = True
while findingFaces:
# Step 1: Gather images
images = []
photoID = 0
print('Capturing Images...')
for photoID in range(numImages):
ret,img = cam.read()
images.append(img)
cv2.imshow('frame',img)
cv2.moveWindow('frame', 0, 0)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
# Step 2: Detect faces in photos
print('Detecting Faces...')
for img in images:
faceImage = getFace(img)
if faceImage is not None:
faceImages.append(faceImage)
if len(faceImages) >= 10:
findingFaces = False
break
return faceImages
"""
Each suspect sits in front of the robot and has their picture
taken. Get 10 face images of each person
Parameters: numPlayers
Returns: faces - list of face images
labels - list of player IDs
"""
def getTrainingData(numPlayers):
faces = []
labels = []
for playerID in range(1,numPlayers+1):
waitString = ('{}, please get ready to take your '
'pictures '.format(playerIDName[playerID]))
input(waitString) # Will begin taking pictures on enter key push
faceImages = takeMugshots()
faces.extend(faceImages)
labels.extend([playerID]*len(faceImages))
return faces,labels
def bark():
#Initializing music
print('bork')
pygame.init()
pygame.mixer.music.load('bark.wav')
#Playing music
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
"""
Initializes each player to have a name associated with their ID
Parameters: numPlayers
Returns: playerIDName - dictionary of form {playerID:playerName}
"""
def getPlayerNames(numPlayers):
for playerID in range(1,numPlayers+1):
playerName = input("What is Player {}'s name: ".format(playerID))
playerIDName[playerID] = playerName
"""
Picks one of the suspects to be the criminal
Parameters: numPlayers
Returns: playerID of suspected criminal
"""
def selectCriminal(numPlayers):
input('Now everyone get in line!') # Waits for input so everyone can be ready
criminal = randint(1, numPlayers) #Select Criminal
print('Selecting Criminal...')
print('The Criminal is ' + str(playerIDName[criminal]))
return criminal
def locateCriminal(numPlayers, predictions, confidences, criminal):
potentialCriminals = [i for i in range(len(predictions)) if predictions[i] == criminal]
numCrim = len(potentialCriminals)
if numCrim == 0:
print('No Criminal Located')
else:
criminalConfidence= min([confidences[i] for i in potentialCriminals])
criminalIdx = confidences.index(criminalConfidence)
robotSeek(numPlayers, criminalIdx+1)
time.sleep(.25)
while True:
if GPIO.input(11):
bark()
break
print('The criminal is in location ' + str(criminalIdx+1))
""" Main function """
def main():
try:
# Initialize SPI
wiringpi.wiringPiSPISetup(0, 500000)
# Initialize to a stop
robotStop()
# Get number of players
numPlayers = input('How many people are playing? ')
numPlayers = int(numPlayers)
# Get Player Names
getPlayerNames(numPlayers)
# Get training data
faces, labels = getTrainingData(numPlayers)
# Train model
print('Training...')
recognizer.train(faces, np.array(labels)) #expects numpy array, not list
# Select criminal
criminal = selectCriminal(numPlayers)
# Scan suspects and Predict
predictions, confidences = scanSuspects(numPlayers, criminal)
# Move to Criminal Location
locateCriminal(numPlayers, predictions, confidences, criminal)
GPIO.cleanup()
except Exception as e:
print('Breaking!')
print(traceback.format_exc())
robotStop()
cv2.destroyAllWindows()
GPIO.cleanup()
if __name__ == "__main__":
main()