Skip to content

Commit a6d2e29

Browse files
authored
Merge pull request larymak#137 from erastusnzula/face_recognition
Face recognition
2 parents ef05b51 + 2002bea commit a6d2e29

File tree

6 files changed

+145
-1
lines changed

6 files changed

+145
-1
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,3 +133,4 @@ cython_debug/
133133
!.vscode/launch.json
134134
!.vscode/extensions.json
135135
.history
136+
.idea

Face_recognition/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea

Face_recognition/images/erastus.png

54.9 KB
Loading

Face_recognition/main.py

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
import os
2+
import winsound
3+
4+
import cv2
5+
import face_recognition
6+
import numpy
7+
8+
9+
class FaceRecognition:
10+
11+
def __init__(self):
12+
self.images = []
13+
self.base_names = []
14+
self.encoded_faces = []
15+
self.path = 'images'
16+
print('please wait my dummy program is busy encoding...')
17+
self.camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
18+
self.known_encoded_faces = []
19+
self.frame_one = None
20+
self.video_capture = None
21+
22+
def save_video_stream(self):
23+
os.makedirs('Security Camera Video', exist_ok=True)
24+
name = 'Video1.avi'
25+
if name in os.listdir('Security Camera Video'):
26+
name = f'{os.path.splitext(name)[0][:-1]}' \
27+
f'{len(os.listdir("Security Camera Video")) + 1}' \
28+
f'{os.path.splitext(name)[1]}'
29+
fourcc = cv2.VideoWriter_fourcc(*'XVID')
30+
self.video_capture = cv2.VideoWriter(os.path.join('Security Camera Video', name),
31+
fourcc, 20.0, (640, 480))
32+
print(f'{name} saving ...')
33+
34+
def known_image_folder(self):
35+
for image in os.listdir(path=self.path):
36+
if not (image.endswith('.jpeg') or image.endswith('.JPG')
37+
or image.endswith('.jpg') or image.endswith(
38+
'.png') or image.endswith('.PNG')):
39+
continue
40+
img = cv2.imread(f"{self.path}/{image}")
41+
self.images += [img]
42+
self.base_names += [os.path.splitext(image)[0]]
43+
44+
def encode_face(self, images):
45+
for image in images:
46+
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
47+
face_encoding = face_recognition.face_encodings(image_rgb)[0]
48+
self.encoded_faces += [face_encoding]
49+
return self.encoded_faces
50+
51+
def run(self):
52+
self.known_image_folder()
53+
self.known_encoded_faces = self.encode_face(self.images)
54+
print("Encoding Complete, camera opening...")
55+
self.save_video_stream()
56+
self.open_camera_tasks()
57+
58+
def open_camera_tasks(self):
59+
while self.camera.isOpened():
60+
_, self.frame_one = self.camera.read()
61+
self.detect_faces()
62+
self.video_capture.write(self.frame_one)
63+
cv2.imshow("Press 'c' to capture image, q to quit.", self.frame_one)
64+
key = cv2.cv2.waitKey(1)
65+
if key == ord('q') or key == 27:
66+
self.exit_protocol()
67+
elif key == ord('c') or key == 32:
68+
self.save_image_capture()
69+
70+
def save_image_capture(self):
71+
os.makedirs('Security Camera Images', exist_ok=True)
72+
name = 'Image1.png'
73+
if name in os.listdir('Security Camera Images'):
74+
name = f"{os.path.splitext(name)[0][:-1]}\
75+
{len(os.listdir('Security Camera Images')) + 1}" \
76+
f"{os.path.splitext(name)[1]}"
77+
cv2.imwrite(os.path.join('Security Camera Images', name), self.frame_one)
78+
print(f"{name} captured successfully.")
79+
80+
def detect_faces(self):
81+
frame_one_rgb = cv2.cvtColor(self.frame_one, cv2.COLOR_BGR2RGB)
82+
face_location = face_recognition.face_locations(frame_one_rgb)
83+
face_encoding = face_recognition.face_encodings(frame_one_rgb, face_location)
84+
for face_encoded, face_located in zip(face_encoding, face_location):
85+
self.face_comparison(face_encoded, face_located)
86+
87+
def face_comparison(self, face_encoded, face_located):
88+
compare_face = face_recognition.compare_faces(self.known_encoded_faces, face_encoded)
89+
face_distance = face_recognition.face_distance(self.known_encoded_faces, face_encoded)
90+
distance_index = numpy.argmin(face_distance)
91+
if compare_face[distance_index]:
92+
name = self.base_names[int(distance_index)].title()
93+
x, y, w, h = face_located
94+
cv2.rectangle(self.frame_one, (h, x), (y, w), (0, 255, 0), 2)
95+
cv2.rectangle(self.frame_one, (h, x-40), (y, w), (0, 255, 0), 2)
96+
cv2.putText(self.frame_one, name, (
97+
h + 30, x - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 255), 2)
98+
else:
99+
x, y, w, h = face_located
100+
cv2.rectangle(self.frame_one, (h, x), (y, w), (0, 255, 0), 2)
101+
cv2.rectangle(self.frame_one, (h, x - 40), (y, w), (0, 255, 0), 2)
102+
cv2.putText(self.frame_one, "Unknown", (h, x - 10),
103+
cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 255),
104+
2)
105+
winsound.PlaySound('alert.wav', winsound.SND_ASYNC)
106+
print("Intruder in the house.")
107+
108+
def exit_protocol(self):
109+
self.camera.release()
110+
self.video_capture.release()
111+
cv2.destroyAllWindows()
112+
113+
114+
if __name__ == "__main__":
115+
FaceRecognition().run()

Face_recognition/readme.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
Face recognition
2+
================
3+
4+
Description
5+
===========
6+
```
7+
* Detect faces in a live camera feed.
8+
* Compare them to directory images.
9+
* Attach a name tag.
10+
```
11+
Packages
12+
========
13+
14+
```
15+
* import os.
16+
* import winsound.
17+
* import cv2.
18+
* import face_recognition.
19+
* import numpy.
20+
```
21+
How it works
22+
============
23+
```
24+
* Clone the project.
25+
* Run main.py.
26+
```

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,5 @@ The contribution guidelines are as per the guide [HERE](https://github.com/larym
9595
| 51 | [PDF Downloader](https://github.com/Sdccoding/Python-project-Scripts/tree/main/PDF_Downloader) | [Souhardya Das Chowdhury](https://github.com/Sdccoding)
9696
| 52 | [ConsoleSnake](https://github.com/larymak/Python-project-Scripts/tree/main/ConsoleSnake) | [tomimara52](https://github.com/tomimara52)
9797
| 52 | [ConsoleMinesweeper](https://github.com/larymak/Python-project-Scripts/tree/main/ConsoleMinesweeper) | [tomimara52](https://github.com/tomimara52)
98-
| 53 | [Drink Water Reminder](https://github.com/larymak/Python-project-Scripts/tree/main/drink-water-reminder) | [Tristán Hdez](https://github.com/tristanHdez18)
98+
99+
| 53 | [Face_recognition](https://github.com/erastusnzula/Python-project-Scripts/tree/face_recognition/Face_recognition) |[erastusnzula](https://github.com/erastusnzula)

0 commit comments

Comments
 (0)