Files
InteraktionProjektTest/test_kinect_light_control.py
T

486 lines
16 KiB
Python
Executable File

#!/usr/bin/env python3
"""Testprogramm für Kinect-basierte Lichtsteuerung (Stairville MH-X25 Moving Head).
Steuerungsumfang gemäß Bedienungsanleitung:
- Feste Helligkeit (Dimmer / Shutter): Ausschaltbar per Geste oder Tastatur
- Pan und Tilt fest eingestellt (Zentriert: 128 / 128)
- Steuerung der Kegelgröße (Groß/Offen, Mittel/Spot, Klein/Pinspot)
- Gobo-Steuerung (Gobos 1-7, Offen, Shake, Rotation)
- Umschaltung zwischen 3 Farben (Weiß, Rot, Blau)
- DMX-Schnittstelle mit automatischem Mock-Modus für Offline-Tests
"""
from __future__ import annotations
import os
import sys
import time
import urllib.request
import cv2
import mediapipe as mp
import numpy as np
from mediapipe.tasks import python as mp_python
from mediapipe.tasks.python import vision as mp_vision
# ------------------------------------------------------------------------------
# 0. WINDOWS DLL-PFAD ABSICHERN (Azure Kinect SDK)
# ------------------------------------------------------------------------------
_dll_dir_handles = []
if sys.platform == "win32":
possible_sdk_paths = [
r"C:\Program Files\Azure Kinect SDK v1.4.2\sdk\windows-desktop\amd64\release\bin",
r"C:\Program Files\Azure Kinect SDK v1.4.1\sdk\windows-desktop\amd64\release\bin",
r"C:\Program Files\Azure Kinect SDK v1.4.0\sdk\windows-desktop\amd64\release\bin",
]
for kinect_bin_path in possible_sdk_paths:
if os.path.exists(kinect_bin_path):
if kinect_bin_path not in os.environ.get("PATH", ""):
os.environ["PATH"] = (
kinect_bin_path + os.pathsep + os.environ.get("PATH", "")
)
if hasattr(os, "add_dll_directory"):
try:
handle = os.add_dll_directory(kinect_bin_path)
_dll_dir_handles.append(handle)
except OSError as e:
print(f"[WARNUNG] Konnte DLL-Verzeichnis nicht registrieren: {e}")
break
try:
from pyk4a import ColorResolution, Config, DepthMode, PyK4A
except ImportError:
PyK4A = None
Config = None
ColorResolution = None
DepthMode = None
from src.light_control.light_control import (
DMXController,
GestureClassifier,
LightState,
NormalizedLandmark,
)
# ------------------------------------------------------------------------------
# 1. KONFIGURATION & MODELL-DOWNLOAD
# ------------------------------------------------------------------------------
MODEL_FILENAME = "pose_landmarker_full.task"
MODEL_URL = (
"https://storage.googleapis.com/mediapipe-models/pose_landmarker/"
"pose_landmarker_full/float16/latest/pose_landmarker_full.task"
)
MIN_FULL_MODEL_BYTES = 8_000_000
def ensure_model_exists(filename: str = MODEL_FILENAME, url: str = MODEL_URL) -> str:
"""Prüft und lädt das MediaPipe Full-Task-Modell bei Bedarf herunter.
Args:
filename: Dateiname der Modelldatei.
url: Download-URL für das Modell.
Returns:
Absoluter Pfad zur Modelldatei.
"""
script_dir = os.path.dirname(os.path.abspath(__file__))
model_path = os.path.join(script_dir, filename)
if (
not os.path.exists(model_path)
or os.path.getsize(model_path) < MIN_FULL_MODEL_BYTES
):
print(f"[INIT] Modell {filename} fehlt oder unvollständig. Starte Download...")
temp_path = model_path + ".download"
try:
urllib.request.urlretrieve(url, temp_path)
os.replace(temp_path, model_path)
print(f"[INIT] Download erfolgreich abgeschlossen: {model_path}")
except Exception as e:
if os.path.exists(temp_path):
os.remove(temp_path)
print(f"[FEHLER] Automatischer Modell-Download fehlgeschlagen: {e}")
raise
return model_path
def render_overlay(
frame: np.ndarray, state: LightState, dmx: DMXController, fps: float
) -> np.ndarray:
"""Zeigt Status, DMX-Werte und Steuerungsoptionen auf dem Bild an.
Args:
frame: BGR-Kamerabild.
state: Aktueller Lichtsteuerungs-Zustand.
dmx: DMXController Instanz.
fps: Aktuelle Bildwiederholrate.
Returns:
Bild mit gerendertem Overlay.
"""
overlay = frame.copy()
cv2.rectangle(overlay, (10, 10), (520, 390), (20, 20, 20), -1)
frame = cv2.addWeighted(overlay, 0.80, frame, 0.20, 0)
# Statuszeile
status_color = (0, 165, 255) if dmx.mock_mode else (0, 255, 0)
status_text = (
"[MODUS: MOCK (Keine DMX-Hardware)]"
if dmx.mock_mode
else f"[MODUS: DMX AKTIV ({dmx.port})]"
)
cv2.putText(
frame,
status_text,
(20, 35),
cv2.FONT_HERSHEY_SIMPLEX,
0.55,
status_color,
2,
)
cv2.putText(
frame,
f"FPS: {fps:4.1f}",
(420, 35),
cv2.FONT_HERSHEY_SIMPLEX,
0.55,
(255, 255, 255),
1,
)
# DMX & Scheinwerfer Status
light_text = (
f"AN (Helligkeit: {state.fixed_brightness:3d} / 255)"
if state.light_on
else "AUS (Dimmer: 0)"
)
light_color = (0, 255, 0) if state.light_on else (0, 0, 255)
cv2.putText(
frame,
f"Licht-Status : {light_text}",
(20, 65),
cv2.FONT_HERSHEY_SIMPLEX,
0.52,
light_color,
2,
)
cv2.putText(
frame,
f"Pan / Tilt : CH1={state.pan:3d} (fest) | CH2={state.tilt:3d} (fest)",
(20, 92),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(200, 200, 200),
1,
)
cv2.putText(
frame,
f"Farbe (CH 6) : {state.color.display_name} (DMX: {state.color.dmx_value:3d})",
(20, 118),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(255, 200, 100),
1,
)
cv2.putText(
frame,
f"Kegelgroesse : {state.cone_size.display_name} (DMX: {state.cone_size.dmx_value:3d})",
(20, 144),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(100, 255, 255),
1,
)
cv2.putText(
frame,
f"Gobo (CH 9) : {state.gobo.display_name} (DMX: {state.gobo.dmx_value:3d})",
(20, 170),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(150, 150, 255),
1,
)
cv2.putText(
frame,
f"Rotation(CH10): {state.gobo_rotation.display_name} (DMX: {state.gobo_rotation.dmx_value:3d})",
(20, 196),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(180, 255, 180),
1,
)
# Trennlinie
cv2.line(frame, (20, 212), (505, 212), (100, 100, 100), 1)
# Steuerungshinweise
cv2.putText(
frame,
"STEUERUNG (GESTEN & TASTATUR):",
(20, 232),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(255, 255, 255),
2,
)
cv2.putText(
frame,
"- Licht AN/AUS : Rechter Arm (hoch=AN, tief=AUS) | [LEER / d]",
(20, 256),
cv2.FONT_HERSHEY_SIMPLEX,
0.44,
(210, 210, 210),
1,
)
cv2.putText(
frame,
"- 3 Farben : Linke Hand (tief=Weiss, Brust=Rot, hoch=Blau)",
(20, 278),
cv2.FONT_HERSHEY_SIMPLEX,
0.44,
(210, 210, 210),
1,
)
cv2.putText(
frame,
" Tasten: [1] Weiss | [2] Rot | [3] Blau | [c] Zyklus",
(20, 298),
cv2.FONT_HERSHEY_SIMPLEX,
0.42,
(180, 180, 180),
1,
)
cv2.putText(
frame,
"- Kegelgroesse : Handabstand (weit=Gross, nah=Klein) | [k]",
(20, 320),
cv2.FONT_HERSHEY_SIMPLEX,
0.44,
(210, 210, 210),
1,
)
cv2.putText(
frame,
"- Gobo-Auswahl : Taste [g] (Gobos 1-7) | [r] Rotation",
(20, 342),
cv2.FONT_HERSHEY_SIMPLEX,
0.44,
(210, 210, 210),
1,
)
cv2.putText(
frame,
"- Beenden : Taste 'q' oder 'ESC'",
(20, 366),
cv2.FONT_HERSHEY_SIMPLEX,
0.45,
(150, 220, 255),
1,
)
return frame
def main() -> None:
"""Hauptfunktion für das Kinect-Lichtsteuerungsprogramm."""
k4a = None
landmarker = None
dmx = None
try:
# 1. MediaPipe PoseLandmarker vorbereiten
print("[INIT] Initialisiere MediaPipe PoseLandmarker...")
model_path = ensure_model_exists()
with open(model_path, "rb") as f:
model_buffer = f.read()
base_options = mp_python.BaseOptions(model_asset_buffer=model_buffer)
options = mp_vision.PoseLandmarkerOptions(
base_options=base_options,
running_mode=mp_vision.RunningMode.IMAGE,
num_poses=1,
min_pose_detection_confidence=0.5,
min_tracking_confidence=0.5,
)
landmarker = mp_vision.PoseLandmarker.create_from_options(options)
print("[INIT] MediaPipe Landmarker betriebsbereit.")
# 2. Azure Kinect Kamera starten
print("[INIT] Starte Azure Kinect DK...")
use_mock_camera = False
cap_cv = None
if PyK4A is not None:
try:
k4a = PyK4A(
Config(
color_resolution=ColorResolution.RES_720P,
depth_mode=DepthMode.NFOV_UNBINNED,
synchronized_images_only=True,
)
)
k4a.start()
print("[INIT] Azure Kinect DK erfolgreich gestartet.")
except (RuntimeError, OSError) as err:
print(f"[WARNUNG] Azure Kinect nicht verfügbar: {err}")
use_mock_camera = True
else:
print("[WARNUNG] PyK4A nicht installiert. Verwende Webcam / Mock-Kamera.")
use_mock_camera = True
if use_mock_camera:
cap_cv = cv2.VideoCapture(0)
if not cap_cv.isOpened():
print(
"[INFO] Keine Standard-Webcam verfügbar. Verwende Testbild-Generator."
)
# 3. DMX-Controller & Lichtstatus initialisieren
dmx = DMXController()
light_state = LightState()
light_state.apply_to_dmx(dmx)
dmx.send()
prev_time = time.time()
print(
"\n[INFO] Lichtsteuerung aktiv. Druecke 'q' oder ESC im Vorschaufenster zum Beenden.\n"
)
while True:
color_bgr = None
if k4a is not None and not use_mock_camera:
try:
capture = k4a.get_capture()
if capture.color is not None:
color_bgr = cv2.cvtColor(capture.color, cv2.COLOR_BGRA2BGR)
except (RuntimeError, OSError) as err:
print(f"[WARNUNG] Frame-Fehler: {err}")
continue
elif cap_cv is not None and cap_cv.isOpened():
ret, frame = cap_cv.read()
if ret:
color_bgr = frame
if color_bgr is None:
# Fallback: Schwarzes Bild erzeugen für Testbetrieb
color_bgr = np.zeros((720, 1280, 3), dtype=np.uint8)
h, w, _ = color_bgr.shape
color_rgb = cv2.cvtColor(color_bgr, cv2.COLOR_BGR2RGB)
# 4. MediaPipe Inferenz & Gestenerkennung
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=color_rgb)
detection_result = landmarker.detect(mp_image)
if (
detection_result.pose_landmarks
and len(detection_result.pose_landmarks) > 0
):
raw_landmarks = detection_result.pose_landmarks[0]
norm_landmarks = [
NormalizedLandmark(
x=lm.x,
y=lm.y,
z=lm.z,
visibility=getattr(lm, "visibility", 1.0),
)
for lm in raw_landmarks
]
# Geste: Licht Ein/Aus (Rechter Arm)
toggle_decision = GestureClassifier.classify_light_toggle(
norm_landmarks
)
if toggle_decision is not None:
light_state.light_on = toggle_decision
# Geste: Farbe (Linke Hand)
detected_color = GestureClassifier.classify_color(norm_landmarks)
if detected_color is not None:
light_state.color = detected_color
# Geste: Kegelgröße (Handabstand)
detected_cone = GestureClassifier.classify_cone_size(norm_landmarks)
if detected_cone is not None:
light_state.cone_size = detected_cone
# Visualisiere Schlüsselgelenke
for idx, col in [
(15, (255, 0, 0)), # Linkes Handgelenk (Blau)
(16, (0, 165, 255)), # Rechtes Handgelenk (Orange)
]:
if idx < len(norm_landmarks):
px = int(norm_landmarks[idx].x * w)
py = int(norm_landmarks[idx].y * h)
cv2.circle(color_bgr, (px, py), 8, col, -1)
# DMX-Daten synchronisieren
light_state.apply_to_dmx(dmx)
dmx.send()
# 5. UI Overlay rendern
now = time.time()
dt = now - prev_time
fps = (1.0 / dt) if dt > 0 else 0.0
prev_time = now
color_bgr = render_overlay(color_bgr, light_state, dmx, fps)
cv2.imshow("Kinect Lichtsteuerung - Stairville MH-X25", color_bgr)
# 6. Tastatursteuerung
key = cv2.waitKey(1) & 0xFF
if key == ord("q") or key == 27:
break
elif key == ord(" ") or key == ord("d"):
light_state.toggle_light()
print(
f"[TASTE] Licht umgeschaltet: {'AN' if light_state.light_on else 'AUS'}"
)
elif key == ord("1"):
light_state.set_color_index(0)
print(f"[TASTE] Farbe gewaehlt: {light_state.color.display_name}")
elif key == ord("2"):
light_state.set_color_index(1)
print(f"[TASTE] Farbe gewaehlt: {light_state.color.display_name}")
elif key == ord("3"):
light_state.set_color_index(2)
print(f"[TASTE] Farbe gewaehlt: {light_state.color.display_name}")
elif key == ord("c"):
light_state.cycle_color()
print(f"[TASTE] Farbzyklus: {light_state.color.display_name}")
elif key == ord("k") or key == ord("z"):
light_state.cycle_cone_size()
print(f"[TASTE] Kegelgroesse: {light_state.cone_size.display_name}")
elif key == ord("g"):
light_state.cycle_gobo()
print(f"[TASTE] Gobo: {light_state.gobo.display_name}")
elif key == ord("r"):
light_state.cycle_gobo_rotation()
print(
f"[TASTE] Gobo Rotation: {light_state.gobo_rotation.display_name}"
)
except KeyboardInterrupt:
print("\n[INFO] Programm durch Benutzer abgebrochen.")
finally:
print("[CLEANUP] Beende Lichtsteuerung und DMX...")
if dmx is not None:
dmx.close()
if landmarker is not None:
landmarker.close()
if k4a is not None:
try:
k4a.stop()
except (RuntimeError, OSError) as err:
print(f"[CLEANUP] Fehler beim Stoppen der Kamera: {err}")
cv2.destroyAllWindows()
print("[CLEANUP] Erfolgreich beendet.")
if __name__ == "__main__":
main()