Skip to main content

Face Recognition System using Python and OpenCV

Page 1


International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 03 | Mar 2026 www.irjet.net p-ISSN: 2395-0072

Face Recognition System using Python and OpenCV

1M.Tech Scholar, Dept. of Computer Science Engineering & Information Technology, Institute of Engineering and Technology, Mangalayatan University, Beswan, Aligarh, India

Abstract - In an age where security and automation are increasingly prioritized, face recognition systems provide an effective and non-intrusive method for identity verification. This paper presents a Face Recognition System built using Python, OpenCV, and the Local Binary Pattern Histogram (LBPH) classifier, with a GUI developed in Tkinter and a MySQL backend. The system covers facial data acquisition, model training, real-time recognition, and database-based user management. Testing on a standard laptop webcam yielded a recognition accuracy of approximately 95% under well-lit, frontal conditions, with recognition time under one second. The system demonstrates high reliability for attendance management and access control in academic or office environments.

Key Words: Face Recognition, LBPH Algorithm, Haar Cascade, OpenCV, Python, Tkinter GUI, MySQL Database, Real-Time Detection

1. INTRODUCTION

Biometricauthenticationhasgainedwidespreadadoption duetoitspotentialtodeliversecureandefficientpersonal identification without physical tokens. Among the various biometric modalities, face recognition stands out as nonintrusive, contactless, and increasingly practical given the ubiquity of cameras in smartphones, laptops, and surveillancesystems[1].Unlikefingerprintoririsscanning, facerecognitionrequiresnophysicalcontact,makingitideal forsituationswherehygieneoreaseofuseisaconcern.

Conventionalattendanceandidentityverificationmethods such as manual roll calls, RFID cards, and PINs are often inefficientandsusceptibletofraud.Cardscanbelost,PINs can be shared, and manual methods consume significant time, especially in large-population environments such as schools, universities, and corporate offices. Biometric methods eliminate proxy attendance and reduce administrativeoverheadsignificantly.

Themotivationbehindthisworkstemsfromtheneedforan automated,accessible,anddeployablesystemthatintegrates computer vision, a user-friendly GUI, and database management into a cohesive application. This paper describes the design, implementation, and evaluation of a completefacerecognitionpipelineusingPythonandOpenCV that operates entirely offline, requires no specialised hardware beyond a standard webcam, and is suitable for deploymentinresource-constrainedenvironments.

1.1 Problem Statement

Existingfacerecognitionsolutionseitherdemandhigh-end GPU hardware (deep learning models) or lack integration with complete workflows including registration, GUI, and persistentstorage.Thereisaclearneedforamodular,and accessible system that can be deployed on standard computerswithoutclouddependency.Theproposedsystem addressesthisgapusingclassicalcomputervisioncombined withastructuredapplicationarchitecture.

1.2 Objectives

Thekeyobjectivesofthisprojectare:(1)DataAcquisition designamoduletocapturediversefacialimagesviawebcam orvideofiles;(2)ClassifierTraining implementtheLBPH algorithm to train per-user recognition models; (3) RealTimeRecognition identifyfacesfromalivewebcamfeed with latency under one second; (4) GUI Development buildanintuitiveTkinter-basedinterfaceaccessibletonontechnical users; (5) Database Integration store and manage user profiles in MySQL; (6) Access Control implementadminloginauthenticationtoprotectthesystem.

1.3 Scope and Limitations

Thesystemisdesignedforcontrolledindoorenvironments such as classrooms, laboratories, and small offices. It supportssingle-facerecognitionpersessionandrequiresan initialenrolmentphase.Recognitionaccuracymaydegrade underpoorlighting,significantheadrotation,orpartialface occlusion. The system does not currently support mask detection, multi-face simultaneous recognition, or cloudbased deployment, though these are identified as future enhancements.

1.4 Technology Stack

Python3.9servesastheprimarylanguageforitsextensive library ecosystem. OpenCV 4.x provides face detection via the Haar Cascade Classifier and recognition via the LBPH recognizer.Tkinterisusedforcross-platformdesktopGUI development. MySQL 8.0 with mysql-connector-python handlespersistentstorage.TheLBPHalgorithmwasselected foritsrobustnessagainstmonotonicilluminationchanges, its support for incremental training, and its built-in availabilitywithinOpenCVwithoutrequiringseparatemodel filesorGPUresources.

International

Volume: 13 Issue: 03 | Mar 2026 www.irjet.net

2. LITERATURE REVIEW

Face recognition research has evolved through several distinctphases.Earlysystemsreliedongeometricmethods thatmeasureddistancesbetweenfaciallandmarkssuchas theeyes,nosetip,andmouthcorners.Whileintuitive,these approachesprovedsensitivetochangesinpose,lighting,and expression.

The1990sandearly2000ssawtheriseofappearance-based statisticalmethods.TurkandPentlandintroducedPrincipal Component Analysis (PCA)-based Eigenfaces, which represented faces as linear combinations of basis vectors derivedfromtrainingdata.Belhumeuretal.extendedthis withLinearDiscriminantAnalysis(LDA)intheFisherfaces method, which maximised inter-class separation while minimisingintra-classvariation.Bothmethodsrepresented significantmilestonesbutremainedlimitedbytheirlinear assumptions.

The deep learning era brought transformative improvements. Taigman et al. (DeepFace, Facebook) achievednear-humanaccuracyontheLFWbenchmarkusing a9-layerdeepneuralnetworkwith3Dalignment[2].Schroff et al. (FaceNet, Google) introduced a triplet-loss-based approach that maps faces into a compact Euclidean embedding space, enabling direct distance-based comparison [3]. VGG-Face (Parkhi et al., Oxford) demonstrated that very deep networks trained on large datasetscouldgeneraliserobustlyacrossdiverseconditions.

Despitetheseadvances,deeplearningmodelsrequireGPU acceleration, datasets of tens of thousands of images, and substantial engineering effort to deploy. For academic prototypesandresource-constrainedapplications,theLocal Binary Patterns Histogram (LBPH) method remains a practicalandwell-validatedchoice[4].LBPHencodeslocal micro-texturebycomparingeachpixeltoitsPneighbourson a circle of radius R, producing a binary pattern. These patterns are accumulated into spatial histograms and compared using chi-square distance or histogram intersectionforrecognition.

2.1 Comparison of Approaches

Table 1:ComparisonofFaceRecognitionApproaches

2.2 Identified Gaps and Proposed Solution

Keygapsinclude:(1)Deep-learningsolutionsdemandGPU hardware unavailable in typical lab settings; (2) Most research prototypes lack integrated GUIs and database backends; (3) Real-world deployment needs offline operationwithoutcloudAPIdependencies;(4)Hardcoded orundocumentedenrolmentpipelineslimitaccessibilityfor non-expertusers.Theproposedsystemaddressesallthese gapsbycombiningLBPHrecognitionwithamodularPython application, Tkinter GUI, and MySQL database, operating entirelyofflineoncommodityhardware.

3. SYSTEM DESIGN & ARCHITECTURE

TheFaceRecognitionSystemisorganisedaroundasixmodulearchitecturethatseparatesconcernscleanlyacross authentication, user interface, data acquisition, model training,recognition,anddatabasemanagement.Thisdesign promotes independent testing and future replacement of individual components without impacting the rest of the application.

Figure1showstheblockdiagramillustratingdataflow:raw webcamframesarecapturedandpre-processed,facesare detectedandcropped,featuresareextractedviaLBPH,and theresultingmodelispersistedforrecognition.Userdatais storedinMySQLthroughoutthepipeline.

1: SystemBlockDiagram

Fig

Volume: 13 Issue: 03 | Mar 2026 www.irjet.net p-ISSN: 2395-0072

3.1 Authentication Module (login_page.py)

The login module presents a minimal Tkinter window requesting admin credentials. Credentials are currently validated against hardcoded values (username: admin, password:admin123).Onsuccess,thesubprocessmodule spawns the main GUI process. This module prevents unauthorisedaccesstosensitiveregistrationandrecognition features. Future work will migrate credential storage to a hasheddatabaserecord.

3.2 Data Acquisition Module (create_dataset.py)

ThemoduleinitialisestheHaarCascadeClassifierandopens the webcam via cv2.VideoCapture(0). For each frame, detectedfaceROIsareconvertedtograyscaleandsavedas JPEG images in a user-specific directory (./data/<username>/). The process terminates after 300 imagesarecaptured,ensuringadequatedatasetvarietyfor LBPH training. An alternative path, take_video(), allows frameextractionfrompre-recordedvideofiles,supporting offlineenrolmentscenarios.

3.3

Classifier Training Module (create_classifier.py)

Allfaceimagesinthedatadirectoryareloaded,convertedto grayscale, and assigned numeric labels corresponding to eachuserfolder.TheLBPHrecognizeriscreatedandtrained using recognizer.train(faces, labels). The radius (R=1), number of neighbours (P=8), grid dimensions (8×8 cells), and histogram comparison method are kept at OpenCV defaults,whichhavebeenempiricallyvalidatedforthisclass of applications. The trained model is saved as an XML file usingrecognizer.save().

3.4

Recognition Module (detector.py)

The recognition engine loads the classifier XML and Haar Cascade,thenentersaframe-processingloop.Eachframeis convertedtograyscaleandscannedforface regionsusing detectMultiScale() with scaleFactor=1.3 and minNeighbors=5. Detected ROIs are passed to recognizer.predict(), returning a (label, confidence) pair. Confidence scores below 50 indicate a match; the user’s name is drawn in green above a green bounding box. Unknown faces receive a red bounding box. A five-second session timeout prevents indefinite loops when no face is present.

3.5 Database Module (db_config.py)

A centralised get_connection() function establishes a mysql.connector connection to the face_recognition database.Theuserstablestoresid(PK),name,age,gender, height, location, and project fields. All GUI registration actionswritetothistable.Separatingtheconnectionlogic into a dedicated module simplifies testing and credential rotationwithoutmodifyingapplicationlogic.

3.6 System Workflow

The end-to-end workflow is: (1) Admin authenticates via loginpage;(2)Newuserdetailsareenteredandregistered in MySQL; (3) Face images are captured and stored; (4) LBPHclassifieristrainedoncapturedimages;(5)Real-time recognitionisinitiatedviawebcam;(6)Recognitionresult displayedwithboundingboxandnamelabel;(7)Check-in statusloggedandconfirmationshownviamessagebox.

4. IMPLEMENTATION & RESULTS

AllmoduleswereimplementedinPython3.9onWindows 10,usingOpenCV4.x,Tkinter,andmysql-connector-python. ThecompletesourcecodespanssevenPythonfilesand is structured for modularity and reusability. The GUI flow begins at the Login Page (Fig. 2), proceeds to the Main Dashboard (Fig. 3), then to face capture (Fig. 4), model trainingconfirmation(Fig.5),andreal-timerecognition(Fig. 6). Message box confirmations (Fig. 7) provide user feedback,whileFig.8showstheMySQLdatabaserecords.

Fig 2: LoginPage–AdminAuthentication
Fig 3:MainDashboard–SignUp,CheckUser,Quit

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 03 | Mar 2026 www.irjet.net p-ISSN: 2395-0072

4.1 Database Schema

Table 2: DatabaseSchema–userstable

project VARCHAR(100) ProjectName

4.2 Folder Structure

The project directory is organised as follows: root-level Pythonscripts(app-gui.py,login_page.py,create_dataset.py, create_classifier.py,detector.py,predict.py,db_config.py);a data/ subdirectory containing haarcascade_frontalface_default.xml,aclassifiers/folderfor trained XML models, and per-user subdirectories storing capturedfaceimages;andaface_recognition.sqlschemafile fordatabaseinitialization

5. TESTING & EVALUATION

Testing was conductedatthreelevels:(1)Unit Testing validatingindividual modulefunctionalityinisolation;(2) Integration Testing verifying seamless end-to-end operation from login to recognition; (3) User Acceptance Testing assessingusabilityandGUIclaritywiththreetest users.ThetestenvironmentcomprisedWindows10,Python

Fig 4: FaceCapture–HaarCascadeBoundingBox
Fig 5: ModelTraining–SuccessConfirmation(301 images)
Fig 6: Real-TimeRecognition–KnownUser(GreenBox)
Fig 7: Check-InConfirmationMessageBox
Fig 8: MySQLDatabase–RegisteredUserRecords

International

Volume: 13 Issue: 03 | Mar 2026 www.irjet.net p-ISSN: 2395-0072

3.9, MySQL 8.0, and a standard integrated laptop webcam operatingat720presolutionwith4GBRAM.

5.1 Unit Test Results

Table 3: UnitTestSummary

Module Test Case

create_dataset.py Capture& saveimages 300+imagesin /data/<name> / ✓ Pass

create_classifier.p y Train&save model XMLmodelfile generated ✓ Pass

detector.py Webcam recognition Correctlabel displayed ✓ Pass

predict.py Video recognition Facelabelled invideo ✓ Pass

db_config.py MySQL connection Connection established ✓ Pass

login_page.py Valid/invali dauth Onlyvalid loginpasses ✓ Pass

5.2 Integration Test Results

Table 4: IntegrationTestResults

LoginSystem Valid& invalid credentials Invalid rejected,valid accepted ✓ Pass

User Registration Adduserwith allfields Recordsaved inMySQL ✓ Pass

FaceCapture Webcam capture session 300images stored correctly ✓ Pass

Model Training Trainfrom storedimages .xmlmodel filecreated ✓ Pass Live Recognition Webcam recognition Nameshown withgreen box ✓ Pass

Video Recognition Predictfrom .mp4file Facecorrectly labelled ✓ Pass

5.3 Performance Metrics

Table 5: SystemPerformanceEvaluation

Rate(well-lit, frontal)

Accuracy(≥300 samples/user)

SystemCrashes/Freezes Noneobserved

5.4 Observations and Limitations

Thesystemperformedbestunderconsistentindoorlighting with the user facing the camera directly. Recognition accuracy improved significantly as training samples increased toward 300 per user, with diminishing returns beyondthatthreshold.HaarCascadedetectionwasobserved tostrugglewithnon-frontalposes(>30°rotation)andlowlight conditions (illuminance <100 lux). The hardcoded admin credentials represent a security limitation for production deployment. The confidence threshold of 50% was empirically determined as the optimal trade-off betweenfalsepositiveandfalsenegativerates.

6. CONCLUSION

This paper presented a complete, GUI-based Face RecognitionSystemusingPythonandOpenCV,achievinga recognitionaccuracyofapproximately95%onastandard laptop webcam under controlled indoor conditions. The LBPH algorithm provided an effective balance between accuracy and computational efficiency, confirming the viability of classical machine vision techniques for realworld biometric identity verification without requiring specialisedhardwareorcloudconnectivity.

The six-module architecture (Authentication, Data Acquisition,ClassifierTraining,Recognition,GUI,Database) proved maintainable and extensible. All six primary objectives data capture, model training, real-time

International Research Journal of Engineering and Technology (IRJET) e-ISSN: 2395-0056

Volume: 13 Issue: 03 | Mar 2026 www.irjet.net p-ISSN: 2395-0072

recognition,GUIinteraction,MySQLintegration,andaccess control were successfully implemented and validated through unit, integration, and user acceptance tests. The system operated stably across all test sessions with no crashesrecorded.

6.1 Future Work

Severalenhancementsareidentifiedforfutureiterations:(1) DeepLearningIntegration replaceLBPHwithFaceNetor ArcFace for higher accuracy under challenging conditions such as varying lighting, pose, and occlusion; (2) AntiSpoofing incorporatelivenessdetectiontopreventreplay attacksusingprinted photosorvideoplayback;(3)MultiFaceRecognition extenddetector.pytoidentifymultiple individuals simultaneously in a single frame; (4) Mobile Application developAndroid/iOSversionsusingKivyor Flutter for portable deployment; (5) Cloud Integration migratemodelstorageanduserrecordstoFirebaseorAWS forcentralisedmulti-siteaccess;(6)AttendanceExport auto-generatedate-stampedCSV/Excelattendancereports; (7) Encrypted Credentials replace hardcoded admin credentialswithbcrypt-hasheddatabaserecords.

ACKNOWLEDGEMENT

The author sincerely thanks the supervisor and faculty members of the Dept. of CSE, AI & ML, Mangalayatan University, for their expert guidance and continuous support. Gratitude is also extended to colleagues and the institute for providing the necessary resources and encouragementthroughoutthisproject.

REFERENCES

[1] R. Szeliski, Computer Vision: Algorithms and Applications,Springer,2010.

[2]G.BradskiandA.Kaehler,LearningOpenCV:Computer VisionwiththeOpenCVLibrary,O'ReillyMedia,2008.

[3]I.Goodfellow,Y.Bengio,andA.Courville,DeepLearning, MITPress,2016.

[4]T.Ahonen,A.Hadid,andM.Pietikäinen,"FaceDescription withLocalBinaryPatterns:ApplicationtoFaceRecognition," IEEETrans.PatternAnalysisandMachineIntelligence,2006.

[5]OpenCVDocumentation:https://docs.opencv.org/

[6]MySQLConnectorforPython: https://dev.mysql.com/doc/connector-python/en/

[7]PythonOfficialDocumentation: https://docs.python.org/3/

BIOGRAPHIES

Nishant Kumar is an M.Tech Scholar in Computer Science with specialization in Artificial Intelligence & Machine Learning (AI & ML) at Mangalayatan University, Aligarh, India. His research interests include computer vision, biometric systems, and machine learning. This Face Recognition System using Python and OpenCV was his M.Techdissertationproject(2023–2025).

Turn static files into dynamic content formats.

Create a flipbook
Face Recognition System using Python and OpenCV by IRJET Journal - Issuu