Commit 4aabf507 authored by Akila's avatar Akila

Face Recognition

parent caf587a5
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.8" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Face_Recog.iml" filepath="$PROJECT_DIR$/.idea/Face_Recog.iml" />
</modules>
</component>
</project>
\ No newline at end of file
MIT License
Copyright (c) 2018 Muhammad Ali Zia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
This diff is collapsed.
This diff is collapsed.
import numpy as np
from PIL import Image
import os, cv2
# Method to train custom classifier to recognize face
def train_classifer(data_dir):
# Read all the images in custom data-set
path = [os.path.join(data_dir, f) for f in os.listdir(data_dir)]
faces = []
ids = []
# Store images in a numpy format and ids of the user on the same index in imageNp and id lists
for image in path:
img = Image.open(image).convert('L')
imageNp = np.array(img, 'uint8')
id = int(os.path.split(image)[1].split(".")[1])
faces.append(imageNp)
ids.append(id)
ids = np.array(ids)
# Train and save classifier
clf = cv2.face.LBPHFaceRecognizer_create()
clf.train(faces, ids)
clf.write("classifier.xml")
train_classifer("data")
\ No newline at end of file
import cv2
# Method to generate dataset to recognize a person
def generate_dataset(img, id, img_id):
# write image in data dir
cv2.imwrite("data/user."+str(id)+"."+str(img_id)+".jpg", img)
# Method to draw boundary around the detected feature
def draw_boundary(img, classifier, scaleFactor, minNeighbors, color, text):
# Converting image to gray-scale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detecting features in gray-scale image, returns coordinates, width and height of features
features = classifier.detectMultiScale(gray_img, scaleFactor, minNeighbors)
coords = []
# drawing rectangle around the feature and labeling it
for (x, y, w, h) in features:
cv2.rectangle(img, (x,y), (x+w, y+h), color, 2)
cv2.putText(img, text, (x, y-4), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 1, cv2.LINE_AA)
coords = [x, y, w, h]
return coords
# Method to detect the features
def detect(img, faceCascade, img_id):
color = {"blue":(255,0,0), "red":(0,0,255), "green":(0,255,0), "white":(255,255,255)}
coords = draw_boundary(img, faceCascade, 1.1, 10, color['blue'], "Face")
# If feature is detected, the draw_boundary method will return the x,y coordinates and width and height of rectangle else the length of coords will be 0
if len(coords)==4:
# Updating region of interest by cropping image
roi_img = img[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]]
# Assign unique id to each user
user_id = 1
# img_id to make the name of each image unique
generate_dataset(roi_img, user_id, img_id)
return img
# Loading classifiers
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Capturing real time video stream. 0 for built-in web-cams, 0 or -1 for external web-cams
video_capture = cv2.VideoCapture(-1)
# Initialize img_id with 0
img_id = 0
while True:
if img_id % 50 == 0:
print("Collected ", img_id," images")
# Reading image from video stream
_, img = video_capture.read()
# Call method we defined above
img = detect(img, faceCascade, img_id)
# Writing processed image in a new window
cv2.imshow("face detection", img)
img_id += 1
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# releasing web-cam
video_capture.release()
# Destroying output window
cv2.destroyAllWindows()
\ No newline at end of file
import cv2
# Method to draw boundary around the detected feature
def draw_boundary(img, classifier, scaleFactor, minNeighbors, color, text):
# Converting image to gray-scale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detecting features in gray-scale image, returns coordinates, width and height of features
features = classifier.detectMultiScale(gray_img, scaleFactor, minNeighbors)
coords = []
# drawing rectangle around the feature and labeling it
for (x, y, w, h) in features:
cv2.rectangle(img, (x,y), (x+w, y+h), color, 2)
cv2.putText(img, text, (x, y-4), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 1, cv2.LINE_AA)
coords = [x, y, w, h]
return coords
# Method to detect the features
def detect(img, faceCascade, eyeCascade, noseCascade, mouthCascade):
color = {"blue":(255,0,0), "red":(0,0,255), "green":(0,255,0), "white":(255,255,255)}
coords = draw_boundary(img, faceCascade, 1.1, 10, color['blue'], "Face")
# If feature is detected, the draw_boundary method will return the x,y coordinates and width and height of rectangle else the length of coords will be 0
if len(coords)==4:
# Updating region of interest by cropping image
roi_img = img[coords[1]:coords[1]+coords[3], coords[0]:coords[0]+coords[2]]
# Passing roi, classifier, scaling factor, Minimum neighbours, color, label text
coords = draw_boundary(roi_img, eyeCascade, 1.1, 12, color['red'], "Eye")
coords = draw_boundary(roi_img, noseCascade, 1.1, 4, color['green'], "Nose")
coords = draw_boundary(roi_img, mouthCascade, 1.1, 20, color['white'], "Mouth")
return img
# Loading classifiers
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyesCascade = cv2.CascadeClassifier('haarcascade_eye.xml')
noseCascade = cv2.CascadeClassifier('Nariz.xml')
mouthCascade = cv2.CascadeClassifier('Mouth.xml')
# Capturing real time video stream. 0 for built-in web-cams, 0 or -1 for external web-cams
video_capture = cv2.VideoCapture(-1)
while True:
# Reading image from video stream
_, img = video_capture.read()
# Call method we defined above
img = detect(img, faceCascade, eyesCascade, noseCascade, mouthCascade)
# Writing processed image in a new window
cv2.imshow("face detection", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# releasing web-cam
video_capture.release()
# Destroying output window
cv2.destroyAllWindows()
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
import cv2
def draw_boundary(img, classifier, scaleFactor, minNeighbors, color, text, clf):
# Converting image to gray-scale
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# detecting features in gray-scale image, returns coordinates, width and height of features
features = classifier.detectMultiScale(gray_img, scaleFactor, minNeighbors)
coords = []
# drawing rectangle around the feature and labeling it
for (x, y, w, h) in features:
cv2.rectangle(img, (x,y), (x+w, y+h), color, 2)
# Predicting the id of the user
id, _ = clf.predict(gray_img[y:y+h, x:x+w])
# Check for id of user and label the rectangle accordingly
if id==1:
cv2.putText(img, "Ali", (x, y-4), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 1, cv2.LINE_AA)
coords = [x, y, w, h]
return coords
# Method to recognize the person
def recognize(img, clf, faceCascade):
color = {"blue": (255, 0, 0), "red": (0, 0, 255), "green": (0, 255, 0), "white": (255, 255, 255)}
coords = draw_boundary(img, faceCascade, 1.1, 10, color["white"], "Face", clf)
return img
# Loading classifier
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Loading custom classifier to recognize
clf = cv2.face.LBPHFaceRecognizer_create()
clf.read("classifier.yml")
# Capturing real time video stream. 0 for built-in web-cams, 0 or -1 for external web-cams
video_capture = cv2.VideoCapture(-1)
while True:
# Reading image from video stream
_, img = video_capture.read()
# Call method we defined above
img = recognize(img, clf, faceCascade)
# Writing processed image in a new window
cv2.imshow("face detection", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# releasing web-cam
video_capture.release()
# Destroying output window
cv2.destroyAllWindows()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment