Compare commits
3 Commits
38eb314626
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28bf41feba | ||
|
|
e25ace8d42 | ||
|
|
921887c912 |
BIN
bildPy/.DS_Store
vendored
BIN
bildPy/.DS_Store
vendored
Binary file not shown.
BIN
bildPy/models/names.pkl
Normal file
BIN
bildPy/models/names.pkl
Normal file
Binary file not shown.
38876
bildPy/models/trained_lbph.yml
Normal file
38876
bildPy/models/trained_lbph.yml
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,76 +1,164 @@
|
|||||||
import cv2
|
import cv2
|
||||||
import os
|
import os
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
import pickle
|
||||||
|
|
||||||
# da wir in src sind , so können wir zu andrem ordner kommen
|
# --- KONFIGURATION ---
|
||||||
|
# Pfade zu den Daten und Modellordnern
|
||||||
RAW_DATA_PFAD = "../data_raw"
|
RAW_DATA_PFAD = "../data_raw"
|
||||||
MODEL_PFAD = "../models"
|
MODEL_PFAD = "../models"
|
||||||
MODEL_FILE = os.path.join(MODEL_PFAD, "trained_lbph.yml") # yml für biometrische Data
|
# Datei für die trainierten biometrischen Daten
|
||||||
NAMES_FILE = os.path.join(MODEL_PFAD, "names.pkl") # für mapping the ids from bio data to real person
|
MODEL_FILE = os.path.join(MODEL_PFAD, "trained_lbph.yml")
|
||||||
|
# Datei für das Mapping von IDs zu Personennamen
|
||||||
|
NAMES_FILE = os.path.join(MODEL_PFAD, "names.pkl")
|
||||||
|
|
||||||
# gesicht detektor erstmal initializieren
|
# Initialisierung des Haar-Cascade-Detektors für die Gesichtserkennung
|
||||||
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
||||||
|
|
||||||
|
# Initialisierung des LBPH-Recognizers [cite: 8]
|
||||||
#LBPH Recognizer initializieren
|
|
||||||
recognizer = cv2.face.LBPHFaceRecognizer_create()
|
recognizer = cv2.face.LBPHFaceRecognizer_create()
|
||||||
|
|
||||||
# dir hersteller
|
|
||||||
def create_directory_if_not_exists(directory):
|
def create_directory_if_not_exists(directory):
|
||||||
|
"""Erstellt den Zielordner, falls dieser nicht existiert."""
|
||||||
if not os.path.exists(directory):
|
if not os.path.exists(directory):
|
||||||
os.makedirs(directory)
|
os.makedirs(directory)
|
||||||
|
|
||||||
# trainiert model
|
|
||||||
def train_model():
|
def train_model():
|
||||||
print("\n-training is angefangen")
|
"""Lädt Bilder, extrahiert Gesichter und trainiert das LBPH-Modell."""
|
||||||
|
print("\n--- Training wird gestartet ---")
|
||||||
faces = []
|
faces = []
|
||||||
ids = []
|
ids = []
|
||||||
names_map = {}
|
names_map = {}
|
||||||
current_id = 0
|
current_id = 0
|
||||||
|
|
||||||
|
|
||||||
# überpruft ob data dir schon exestiert
|
|
||||||
if not os.path.exists(RAW_DATA_PFAD):
|
if not os.path.exists(RAW_DATA_PFAD):
|
||||||
print(f"Error: Directory '{RAW_DATA_PFAD}' nicht gefunden.")
|
print(f"Fehler: Ordner '{RAW_DATA_PFAD}' nicht gefunden.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Durchläuft alle Personen-Ordner in data_raw
|
||||||
# geht durch jede ordner in data raw (e.g., diddy, kirk, etc.)
|
|
||||||
for person_name in os.listdir(RAW_DATA_PFAD):
|
for person_name in os.listdir(RAW_DATA_PFAD):
|
||||||
person_path = os.path.join(RAW_DATA_PFAD, person_name)
|
person_path = os.path.join(RAW_DATA_PFAD, person_name)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# verpasst (skip) alles was nicht ordner ist so wie store.ds oder sowas (.txt....)
|
|
||||||
if not os.path.isdir(person_path):
|
if not os.path.isdir(person_path):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
names_map[current_id] = person_name
|
names_map[current_id] = person_name
|
||||||
print(f"Processing ID {current_id}: {person_name}")
|
print(f"Verarbeite Person: {person_name} (ID: {current_id})")
|
||||||
|
|
||||||
# geht durch jedes Bild in der Ordner jeder Person
|
|
||||||
for image_name in os.listdir(person_path):
|
for image_name in os.listdir(person_path):
|
||||||
|
if image_name.startswith("."):
|
||||||
if image_name.startswith("."): continue # Skip unsichbare files die mit . starten
|
continue
|
||||||
|
|
||||||
image_path = os.path.join(person_path, image_name)
|
image_path = os.path.join(person_path, image_name)
|
||||||
|
|
||||||
# ladet das bild hoch dann convertiert zum Grayscale
|
|
||||||
img = cv2.imread(image_path)
|
img = cv2.imread(image_path)
|
||||||
if img is None: continue
|
|
||||||
|
if img is None:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Konvertierung in Graustufen für die LBP-Extraktion [cite: 36]
|
||||||
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
||||||
|
|
||||||
|
# Gesichter im Bild erkennen
|
||||||
#detectiert gesichte
|
|
||||||
faces_rects = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
|
faces_rects = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
|
||||||
|
|
||||||
for (x, y, w, h) in faces_rects:
|
for (x, y, w, h) in faces_rects:
|
||||||
# region von interest ist das gesicht selbst
|
# Gesichtsbereich (ROI) ausschneiden
|
||||||
roi = gray[y:y + w, x:x + h]
|
roi = gray[y:y + h, x:x + w]
|
||||||
faces.append(roi)
|
faces.append(roi)
|
||||||
ids.append(current_id)
|
ids.append(current_id)
|
||||||
|
|
||||||
current_id += 1
|
current_id += 1
|
||||||
|
|
||||||
if len(faces) == 0:
|
if len(faces) == 0:
|
||||||
print("No faces found. Please check your 'data_raw' folder.")
|
print("Fehler: Keine Gesichter im 'data_raw' Ordner gefunden.")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Modell mit den gesammelten Gesichtern trainieren
|
||||||
|
print(f"Training mit {len(faces)} Gesichtsproben läuft...")
|
||||||
|
recognizer.train(faces, np.array(ids))
|
||||||
|
|
||||||
|
# Modell und Namenszuordnung speichern
|
||||||
|
create_directory_if_not_exists(MODEL_PFAD)
|
||||||
|
recognizer.write(MODEL_FILE)
|
||||||
|
with open(NAMES_FILE, 'wb') as f:
|
||||||
|
pickle.dump(names_map, f)
|
||||||
|
|
||||||
|
print(f"Erfolg! Modell gespeichert unter: {MODEL_FILE}")
|
||||||
|
|
||||||
|
|
||||||
|
def recognize_faces():
|
||||||
|
"""Startet die Live-Erkennung über die Webcam."""
|
||||||
|
print("\n--- Live-Erkennung gestartet ---")
|
||||||
|
|
||||||
|
if not os.path.exists(MODEL_FILE) or not os.path.exists(NAMES_FILE):
|
||||||
|
print("Fehler: Kein trainiertes Modell gefunden. Bitte zuerst Option 1 wählen.")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Modell und Namen laden
|
||||||
|
recognizer.read(MODEL_FILE)
|
||||||
|
with open(NAMES_FILE, 'rb') as f:
|
||||||
|
names_map = pickle.load(f)
|
||||||
|
|
||||||
|
# Webcam-Stream öffnen
|
||||||
|
cap = cv2.VideoCapture(0)
|
||||||
|
print("Info: Drücke 'q', um die Erkennung zu beenden.")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
ret, frame = cap.read()
|
||||||
|
if not ret:
|
||||||
|
break
|
||||||
|
|
||||||
|
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
||||||
|
faces_rects = face_cascade.detectMultiScale(gray, 1.2, 5)
|
||||||
|
|
||||||
|
for (x, y, w, h) in faces_rects:
|
||||||
|
roi_gray = gray[y:y + h, x:x + w]
|
||||||
|
|
||||||
|
# Vorhersage treffen (ID und Confidence-Wert) [cite: 48, 49]
|
||||||
|
# Hinweis: Ein niedrigerer Confidence-Wert bedeutet eine höhere Genauigkeit bei LBPH.
|
||||||
|
id_, confidence = recognizer.predict(roi_gray)
|
||||||
|
|
||||||
|
if confidence < 85: # Schwellenwert für die Erkennung [cite: 49]
|
||||||
|
name = names_map[id_]
|
||||||
|
prozent = f"{round(100 - confidence)}%"
|
||||||
|
else:
|
||||||
|
name = "Unbekannt"
|
||||||
|
prozent = f"{round(100 - confidence)}%"
|
||||||
|
|
||||||
|
# Farbe festlegen: Grün für bekannt, Rot für unbekannt
|
||||||
|
color = (0, 255, 0) if name != "Unbekannt" else (0, 0, 255)
|
||||||
|
|
||||||
|
# Rahmen und Text im Bild einblenden
|
||||||
|
cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
|
||||||
|
cv2.putText(frame, f"{name} ({prozent})", (x, y - 10),
|
||||||
|
cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2)
|
||||||
|
|
||||||
|
cv2.imshow("Klassenprojekt - LBPH Gesichtserkennung", frame)
|
||||||
|
|
||||||
|
if cv2.waitKey(1) & 0xFF == ord('q'):
|
||||||
|
break
|
||||||
|
|
||||||
|
cap.release()
|
||||||
|
cv2.destroyAllWindows()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
while True:
|
||||||
|
print("\n=== LBPH GESICHTSERKENNUNG MENÜ ===")
|
||||||
|
print("1. Modell trainieren")
|
||||||
|
print("2. Live-Erkennung starten (Webcam)")
|
||||||
|
print("3. Beenden")
|
||||||
|
|
||||||
|
wahl = input("Wähle eine Option (1-3): ")
|
||||||
|
|
||||||
|
if wahl == '1':
|
||||||
|
train_model()
|
||||||
|
elif wahl == '2':
|
||||||
|
recognize_faces()
|
||||||
|
elif wahl == '3':
|
||||||
|
print("Programm beendet.")
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
print("Ungültige Eingabe.")
|
||||||
Reference in New Issue
Block a user