Compare commits

...

20 Commits
0.3 ... master

Author SHA1 Message Date
fb84cf1bb5 Formatting 2019-01-22 20:28:13 +03:00
a82b98154f Parenthases 2019-01-18 02:30:19 +03:00
4441616ef1 futre function 2018-12-12 21:59:05 +03:00
96c2d4ccc3 semi colon 2018-12-12 21:56:33 +03:00
00b476ee0b Merge branch 'master' of https://heshamgit.ddns.net/Hesham/FaceRecognition-python 2018-12-12 21:35:56 +03:00
c43128f6f5 Update 'README.md' 2018-12-12 21:16:24 +03:00
48dbd127a2 splitting into functions 2018-12-06 18:01:53 +03:00
HeshamTB
e6de56c167 unknown folder 2018-12-04 20:31:23 +00:00
883d8a6697 Added png to gitignore 2018-12-04 22:49:02 +03:00
HeshamTB
d11220d70c added date for unknown faces 2018-12-04 19:03:00 +00:00
29fa3a3335 Merge branch 'screen-shot-mod' of Hesham/FaceRecognition-python into master 2018-12-04 20:55:02 +03:00
HeshamTB
ef8332f253 Exception handle 2018-12-04 17:38:13 +00:00
HeshamTB
3660a2e9eb save unknown & exception handling & performance 2018-12-04 17:21:15 +00:00
HeshamTB
7d37fa8d91 Celebration 2018-11-30 21:05:38 +00:00
HeshamTB
8ff03abb53 merge 2018-11-30 11:11:40 +00:00
HeshamTB
c6c7a80cee Performace enhancment 2018-11-30 10:54:17 +00:00
HeshamTB
e773fc6a8e exception handling 2018-11-30 10:48:06 +00:00
HeshamTB
4f88480583 exception handling 2018-11-30 10:45:40 +00:00
HeshamTB
a8990873ba Updated if person 2018-11-30 10:37:53 +00:00
HeshamTB
8e351a1df0 update 2018-11-30 10:13:21 +00:00
10 changed files with 270572 additions and 209 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
*.[Jj][Pp][Gg]
*.pyc
*.suo
*.png

17
.project Normal file
View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>FaceRecognition-python</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>

5
.pydevproject Normal file
View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?><pydev_project>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python interpreter</pydev_property>
</pydev_project>

View File

@ -1 +1 @@
### Python code to run in Raspberry Pi with PiCamera to recognize certin faces and send a Serial signal 'o' to be received by arduino.
### Python code to run in Raspberry Pi with PiCamera to recognize certin faces.

View File

@ -7,7 +7,9 @@ const int buzzerPin = 3;
int inputVal = 0;
long duration;
int distance;
char piInput = 'N';
boolean IROK = false;
boolean UltraOK = false;
char pi = 'N';
void setup() {
pinMode(trigPin, OUTPUT);
@ -24,35 +26,35 @@ void setup() {
void loop() {
IROK = false;
UltraOK = false;
pi = 'N';
boolean IROK = false;
boolean UltraOK = false;
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
distance = readDistance();
if (distance < 70) UltraOK = true;
else UltraOK = false;
if (digitalRead(ProxSensor) == LOW ) IROK = true;
else IROK = false;
char pi = 'N';
if (Serial.available() > 0) { pi = Serial.read(); }
if (Serial.available() > 0) {
pi = Serial.read();
}
delay(500);
Serial.println(pi);
Serial.println(IROK);
Serial.println(UltraOK);
//if (IROK && UltraOK) Serial.println("A");
if (IROK && UltraOK && pi == 'o') {
//if (Serial.read() == 'o') {
openShifter();
}
IROK = false;
UltraOK = false;
}
void openShifter() {
digitalWrite(relayPin, HIGH);
playBuzzer(300, true);
delay(7000);
@ -61,10 +63,6 @@ void loop() {
UltraOK = false;
pi = 'N';
serialFlush();
//}
}
IROK = false;
UltraOK = false;
}
void serialFlush() {
@ -84,10 +82,17 @@ void playBuzzer(int time, boolean ok){
}
int readDistance() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
return duration * 0.034 / 2;
}

73686
faces/h Normal file

File diff suppressed because it is too large Load Diff

196621
faces/m

File diff suppressed because it is too large Load Diff

View File

@ -1 +1 @@
["", "Hesham", "Saeed"]
["", "Hesham", "Aidarous"]

84
main.py
View File

@ -1,10 +1,11 @@
from time import sleep
from io import BytesIO
from PIL import Image
import os
import serial
import sys
import json
import datetime
try:
import numpy as np
@ -18,7 +19,7 @@ except Exception as ex:
def init():
go = True
print('Initilizing Camera and cascade components..')
print('Initilizing..')
try:
camera = PiCamera()
camera.resolution = (640, 480)
@ -35,66 +36,82 @@ def init():
except:
print('[ Error ] Can not load cascade File')
go = False
try:
os.mkdir('unknown')
except OSError as ex:
print('Found (unknown) folder')
if (go):
print('Starting Photo loop..')
print('Known people are '+str(loadNames()))
start(camera, face_cascade)
else:
print('closing')
#else:
#print('Sensors not Satisfied')
def start( camera, face_cascade):
j = 0
rawCapture = PiRGBArray(camera)
#camera.framerate = 32
#rawCapture = PiRGBArray(camera, size=(640, 480))
#for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
face_recognizer = cv2.createLBPHFaceRecognizer()
face_recognizer.load('faces/h')
names = loadNames()
while 1:
#try:
#camera.capture('img.jpg')
#img = cv2.imread('img.jpg',1)
try:
camera.capture(rawCapture, format="bgr")
except:
print('[ Error ] Can not capture image. Restarting..')
init()
img = rawCapture.array
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.2,5)
i = 0;
faces = face_cascade.detectMultiScale(gray, 1.3,5)
i = 0
for (x,y,w,h) in faces:
i += 1
j += 1
try:
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
person = recognize(roi_gray)
if person == 'Hesham' or person == 'Saeed':#Change to if 'unknown' elif openShifter
person = recognize(roi_gray, face_recognizer, names)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),1)
cv2.putText(img, person, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.7, (0,255,0), 2)
except:
print('[ Error ] Recognition fail')
if person == 'unknown':
print('Found unknown person')
try:
RGBImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
image = Image.fromarray(RGBImage)
image.save('unknown/'+str(datetime.datetime.now())+'.png')
except Exception as ex :
print('[ Error ] Saving unkown fail')
print(ex)
else:
print('Found '+person)
OpenShifter()
print('Sending to Arduino!')
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.putText(img, person, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.7, (255, 0, 0), 2)
cv2.imshow('image',img)
cv2.waitKey(100)
cv2.waitKey(1)
rawCapture.truncate(0)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
#except:
#print('[ Error ] Unexpected exception')
#print('Closing')
#break
def recognize(image):
names = loadNames()
face_recognizer = cv2.createLBPHFaceRecognizer()
face_recognizer.load('faces/m')
def recognize(image,face_recognizer, names):
try:
img = image.copy()
label= face_recognizer.predict(img)
if label[1] > 120:
except:
print('[ Error ] Error in Recognize() function')
if label[1] > 70:
print(str(label))
return 'unknown'
else:
print(str(label) + ' >>'+names[label[0]])
return names[label[0]]
#def DrawSquares(image,gray,faces,color):
def OpenShifter():
try:
ser = serial.Serial('/dev/ttyUSB0',9600)
@ -102,13 +119,22 @@ def OpenShifter():
ser.write('o')
ser.close()
except Exception as ex:
print('[ Error ] Can not connect to Arduino at /dev/ttyUSB0 ..')
try:
ser = serial.Serial('/dev/ttyUSB1',9600)
ser.open()
ser.write('o')
ser.close()
except:
print('[ Error ] Can not connect to Arduino at /dev/ttyUSB1 ..')
def loadNames():
try:
with open("faces/names.json", "r") as read_file:
data = json.load(read_file)
return list(data)
except:
print('[ Error ] Error in loadNames() function')
init()

View File

@ -7,10 +7,10 @@ import os
import sys
import json
picCount = 0
new = False
def start():
print('Starting training..')
label = int(input('Label (Integer): '))
@ -32,12 +32,14 @@ def start():
addPerson(label, newFileName, oldFileName)
addName(name)
def clearTrainFolder():
print('clearing train folder')
filelist = [f for f in os.listdir('train/') if f.endswith(".jpg")]
for f in filelist:
os.remove(os.path.join('train/', f))
def addPerson(label, newFileName, oldFileName):
try:
# faceFilePath = '/faces/hesham-saeed2'
@ -45,9 +47,9 @@ def addPerson(label, newFileName, oldFileName):
face_recognizer = cv2.createLBPHFaceRecognizer()
global new
if new:
print 'new file. skipping load function'
print('new file. skipping load function')
else:
print 'loading old file'
print('loading old file')
face_recognizer.load(faceFile)
except:
print('[ Error ] Problem in init/loading LBPHfacerecognizer')
@ -76,6 +78,7 @@ def addPerson(label, newFileName, oldFileName):
face_recognizer.save('faces/' + newFileName)
print('Updated and saved file in faces/' + newFileName)
def capture(count):
try:
print('Initializing camera')
@ -97,6 +100,7 @@ def capture(count):
cv2.destroyAllWindows()
print('Done!')
def promptNew():
filemode = raw_input('Make new File? (y/n): ')
if filemode == 'y':
@ -107,8 +111,8 @@ def promptNew():
print('incorrect input')
promptNew()
def addName(newName):
def addName(newName):
with open("faces/names.json", "r") as read_file:
exist = False
namesJson = json.load(read_file)
@ -125,3 +129,5 @@ def addName(newName):
with open("faces/names.json", "w") as write_file:
json.dump(names, write_file)
start()