Bhanumani12 commited on
Commit
1561480
·
verified ·
1 Parent(s): d853b70

Create trainImage.py

Browse files
Files changed (1) hide show
  1. trainImage.py +42 -0
trainImage.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import numpy as np
4
+
5
+ def TrainImages():
6
+ # Path to the training images
7
+ trainimage_path = "TrainingImage"
8
+
9
+ # Prepare for face recognition
10
+ recognizer = cv2.face.LBPHFaceRecognizer_create()
11
+ detector = cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")
12
+
13
+ faces = []
14
+ ids = []
15
+
16
+ # Get all student directories
17
+ for dir_name in os.listdir(trainimage_path):
18
+ student_path = os.path.join(trainimage_path, dir_name)
19
+
20
+ # Check if it's a directory
21
+ if os.path.isdir(student_path):
22
+ for filename in os.listdir(student_path):
23
+ img_path = os.path.join(student_path, filename)
24
+
25
+ # Read image
26
+ img = cv2.imread(img_path)
27
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
28
+
29
+ # Detect faces
30
+ faces_detected = detector.detectMultiScale(gray, 1.3, 5)
31
+
32
+ for (x, y, w, h) in faces_detected:
33
+ # Add the face and associated ID
34
+ faces.append(gray[y:y + h, x:x + w])
35
+ ids.append(int(dir_name))
36
+
37
+ # Train the recognizer
38
+ recognizer.train(faces, np.array(ids))
39
+
40
+ # Save the model to file
41
+ recognizer.write("trainer.yml")
42
+ print("Model trained successfully!")