Compare commits

..

4 Commits

Author SHA1 Message Date
Omar taky
c3a96226e8 Merge branch 'main' of https://git.bib.de/PBT3H24AEH/Python_App 2026-02-06 12:19:10 +01:00
Omar taky
7dec1a802b add jd pic 2026-02-06 12:19:08 +01:00
6a0b90aad8 bildPy/data_raw/.DS_Store gelöscht 2026-02-06 12:00:23 +01:00
54a0f0ccb8 bildPy/.DS_Store gelöscht 2026-02-06 11:57:02 +01:00
15 changed files with 0 additions and 39082 deletions

BIN
bildPy/.DS_Store vendored

Binary file not shown.

10
bildPy/.idea/.gitignore generated vendored
View File

@@ -1,10 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

1
bildPy/.idea/.name generated
View File

@@ -1 +0,0 @@
source.py

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="jdk" jdkName="Python 3.14" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

7
bildPy/.idea/misc.xml generated
View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.14" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.14" project-jdk-type="Python SDK" />
</project>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/bildPy.iml" filepath="$PROJECT_DIR$/.idea/bildPy.iml" />
</modules>
</component>
</project>

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

File diff suppressed because it is too large Load Diff

View File

@@ -1,164 +0,0 @@
import cv2
import os
import numpy as np
import pickle
# --- KONFIGURATION ---
# Pfade zu den Daten und Modellordnern
RAW_DATA_PFAD = "../data_raw"
MODEL_PFAD = "../models"
# Datei für die trainierten biometrischen Daten
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")
# Initialisierung des Haar-Cascade-Detektors für die Gesichtserkennung
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Initialisierung des LBPH-Recognizers [cite: 8]
recognizer = cv2.face.LBPHFaceRecognizer_create()
def create_directory_if_not_exists(directory):
"""Erstellt den Zielordner, falls dieser nicht existiert."""
if not os.path.exists(directory):
os.makedirs(directory)
def train_model():
"""Lädt Bilder, extrahiert Gesichter und trainiert das LBPH-Modell."""
print("\n--- Training wird gestartet ---")
faces = []
ids = []
names_map = {}
current_id = 0
if not os.path.exists(RAW_DATA_PFAD):
print(f"Fehler: Ordner '{RAW_DATA_PFAD}' nicht gefunden.")
return
# Durchläuft alle Personen-Ordner in data_raw
for person_name in os.listdir(RAW_DATA_PFAD):
person_path = os.path.join(RAW_DATA_PFAD, person_name)
if not os.path.isdir(person_path):
continue
names_map[current_id] = person_name
print(f"Verarbeite Person: {person_name} (ID: {current_id})")
for image_name in os.listdir(person_path):
if image_name.startswith("."):
continue
image_path = os.path.join(person_path, image_name)
img = cv2.imread(image_path)
if img is None:
continue
# Konvertierung in Graustufen für die LBP-Extraktion [cite: 36]
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Gesichter im Bild erkennen
faces_rects = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
for (x, y, w, h) in faces_rects:
# Gesichtsbereich (ROI) ausschneiden
roi = gray[y:y + h, x:x + w]
faces.append(roi)
ids.append(current_id)
current_id += 1
if len(faces) == 0:
print("Fehler: Keine Gesichter im 'data_raw' Ordner gefunden.")
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.")