-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencodings.py
More file actions
57 lines (53 loc) · 2.25 KB
/
encodings.py
File metadata and controls
57 lines (53 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import os
import pickle
import cv2
import face_recognition
import numpy as np
# Dataset path
dataset_folder = r"C:\Users\admin\Desktop\FR_1\dataset"
encoding_file = "encodings.pkl"
def process_image(image_path):
"""Loads an image, converts it, resizes, detects face & encodes it."""
try:
# Load image using OpenCV
image = cv2.imread(image_path)
if image is None:
print(f"❌ Failed to load {image_path}")
return None, None
# Resize image for better face detection
image = cv2.resize(image, (600, 600))
rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Detect faces using CNN model
face_locations = face_recognition.face_locations(rgb_image, model="cnn")
if not face_locations:
print(f"❌ No face detected in {os.path.basename(image_path)}")
return None, None
# Encode the first face found
face_encodings = face_recognition.face_encodings(rgb_image, face_locations)
if face_encodings:
print(f"✅ Face encoded: {os.path.basename(image_path)}")
return os.path.basename(image_path), face_encodings[0]
else:
print(f"❌ No encoding found in {os.path.basename(image_path)}")
return None, None
except Exception as e:
print(f"❌ Error processing {os.path.basename(image_path)}: {e}")
return None, None
def save_encodings():
"""Loads dataset images, encodes faces, and saves to a file."""
encodings, filenames = [], []
image_files = [os.path.join(dataset_folder, f) for f in os.listdir(dataset_folder) if f.lower().endswith((".jpg", ".jpeg", ".png", ".gif"))]
print(f"📂 Found {len(image_files)} images in dataset.")
for image_path in image_files:
filename, encoding = process_image(image_path)
if encoding is not None:
filenames.append(filename)
encodings.append(encoding)
else:
print(f"🔍 Skipping {os.path.basename(image_path)} due to encoding failure.")
# Save encodings
with open(encoding_file, "wb") as f:
pickle.dump((np.array(encodings, dtype=np.float32), filenames), f)
print(f"✅ Saved {len(encodings)} encodings.")
# Run encoding process
save_encodings()