493 lines
15 KiB
Python
Executable File
493 lines
15 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
|
|
from pathlib import Path
|
|
|
|
# Projekt-Wurzelverzeichnis für Imports verfügbar machen
|
|
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
if str(PROJECT_ROOT) not in sys.path:
|
|
sys.path.insert(0, str(PROJECT_ROOT))
|
|
|
|
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 == "win64":
|
|
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.
|
|
"""
|
|
model_path = PROJECT_ROOT / filename
|
|
|
|
if not model_path.exists() or model_path.stat().st_size < MIN_FULL_MODEL_BYTES:
|
|
print(f"[INIT] Modell {filename} fehlt oder unvollständig. Starte Download...")
|
|
temp_path = str(model_path) + ".download"
|
|
try:
|
|
urllib.request.urlretrieve(url, temp_path)
|
|
os.replace(temp_path, str(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 str(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: OpenCV BGR-Bildarray.
|
|
state: Aktueller Zustand des Scheinwerfers.
|
|
dmx: Aktive DMXController-Instanz.
|
|
fps: Aktuelle Bildwiederholrate.
|
|
|
|
Returns:
|
|
BGR-Bild mit gezeichnetem Overlay.
|
|
"""
|
|
overlay = frame.copy()
|
|
cv2.rectangle(overlay, (10, 10), (560, 420), (20, 20, 20), -1)
|
|
frame = cv2.addWeighted(overlay, 0.75, frame, 0.25, 0)
|
|
|
|
# 1. Verbindungs- & Hardwarestatus
|
|
if dmx.mock_mode:
|
|
cv2.putText(
|
|
frame,
|
|
"[MODUS: MOCK (Keine DMX-Hardware)]",
|
|
(20, 35),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.55,
|
|
(0, 165, 255),
|
|
2,
|
|
)
|
|
else:
|
|
cv2.putText(
|
|
frame,
|
|
f"[MODUS: DMX AKTIV ({dmx.port})]",
|
|
(20, 35),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.55,
|
|
(0, 255, 0),
|
|
2,
|
|
)
|
|
|
|
cv2.putText(
|
|
frame,
|
|
f"FPS: {fps:4.1f}",
|
|
(460, 35),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.55,
|
|
(255, 255, 255),
|
|
1,
|
|
)
|
|
|
|
# 2. Scheinwerfer-Zustand
|
|
light_str = "AN" if state.light_on else "AUS"
|
|
light_col = (0, 255, 0) if state.light_on else (0, 0, 255)
|
|
cv2.putText(
|
|
frame,
|
|
f"Licht-Status : {light_str}",
|
|
(20, 65),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.55,
|
|
light_col,
|
|
2,
|
|
)
|
|
|
|
dimmer_val = dmx.get_channel(8)
|
|
shutter_val = dmx.get_channel(7)
|
|
cv2.putText(
|
|
frame,
|
|
f"Dimmer / Shutter : {dimmer_val:3d} (CH8) | {shutter_val:3d} (CH7)",
|
|
(20, 90),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.50,
|
|
(200, 200, 200),
|
|
1,
|
|
)
|
|
|
|
pan_val = dmx.get_channel(1)
|
|
tilt_val = dmx.get_channel(2)
|
|
cv2.putText(
|
|
frame,
|
|
f"Pan / Tilt (Fest): {pan_val:3d} (CH1) | {tilt_val:3d} (CH2)",
|
|
(20, 115),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.50,
|
|
(0, 255, 255),
|
|
1,
|
|
)
|
|
|
|
cv2.putText(
|
|
frame,
|
|
f"Farbe : {state.color.display_name} (CH6: {dmx.get_channel(6)})",
|
|
(20, 140),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.50,
|
|
(255, 180, 180),
|
|
1,
|
|
)
|
|
|
|
cv2.putText(
|
|
frame,
|
|
f"Kegelgroesse : {state.cone_size.display_name}",
|
|
(20, 165),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.50,
|
|
(255, 255, 100),
|
|
1,
|
|
)
|
|
|
|
cv2.putText(
|
|
frame,
|
|
f"Gobo / Rotation : {state.gobo.display_name} | {state.gobo_rotation.display_name}",
|
|
(20, 190),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.50,
|
|
(180, 255, 180),
|
|
1,
|
|
)
|
|
|
|
# Trennlinie
|
|
cv2.line(frame, (20, 205), (540, 205), (100, 100, 100), 1)
|
|
|
|
# 3. Interaktions- & Steuerungshinweise
|
|
cv2.putText(
|
|
frame,
|
|
"BEDIENUNG & GESTENSTEUERUNG:",
|
|
(20, 228),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.50,
|
|
(255, 255, 255),
|
|
2,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [LEERTASTE] / [R-Arm]: Licht AN (Arm hoch) / AUS (Arm tief)",
|
|
(20, 252),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(220, 220, 220),
|
|
1,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [C] / [L-Arm] : Farbe (Weiss/Huefte, Rot/Brust, Blau/Hoch)",
|
|
(20, 274),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(220, 220, 220),
|
|
1,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [K] / [Handabstand] : Kegelgroesse (Gross, Mittel, Klein)",
|
|
(20, 296),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(220, 220, 220),
|
|
1,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [G] : Gobo wechseln (Offen, Gobo 1-7, Shake)",
|
|
(20, 318),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(220, 220, 220),
|
|
1,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [R] : Gobo-Rotation wechseln",
|
|
(20, 340),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(220, 220, 220),
|
|
1,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [1/2/3] : Direktfarbe (1: Weiss, 2: Rot, 3: Blau)",
|
|
(20, 362),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(220, 220, 220),
|
|
1,
|
|
)
|
|
cv2.putText(
|
|
frame,
|
|
"- [Q] / [ESC] : Programm beenden",
|
|
(20, 386),
|
|
cv2.FONT_HERSHEY_SIMPLEX,
|
|
0.45,
|
|
(150, 220, 255),
|
|
1,
|
|
)
|
|
|
|
return frame
|
|
|
|
|
|
def run_light_control_test() -> None:
|
|
"""Hauptfunktion für den interaktiven Testlauf der Lichtsteuerung."""
|
|
print("=" * 70)
|
|
print(" Kinect & DMX Lichtsteuerung - Stairville MH-X25 Test")
|
|
print("=" * 70)
|
|
|
|
# 1. MediaPipe Landmarker laden
|
|
print("\n[1/3] Initialisiere MediaPipe Pose Landmarker...")
|
|
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(" -> MediaPipe Landmarker betriebsbereit.")
|
|
|
|
# 2. Kamera initialisieren
|
|
print("\n[2/3] Initialisiere Kamera (Azure Kinect / OpenCV Fallback)...")
|
|
k4a = None
|
|
use_mock_camera = False
|
|
cap_cv = None
|
|
|
|
if PyK4A is not None:
|
|
try:
|
|
k4a = PyK4A(
|
|
Config(
|
|
color_resolution=ColorResolution.RES_720P,
|
|
depth_mode=DepthMode.OFF,
|
|
synchronized_images_only=False,
|
|
)
|
|
)
|
|
k4a.start()
|
|
print(" -> Azure Kinect DK erfolgreich initialisiert.")
|
|
except (RuntimeError, OSError) as err:
|
|
print(f"[WARNUNG] Azure Kinect konnte nicht gestartet werden: {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 zum Beenden.\n")
|
|
|
|
try:
|
|
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:
|
|
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)),
|
|
(16, (0, 165, 255)),
|
|
]:
|
|
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()
|
|
elif key == ord("1"):
|
|
light_state.set_color_index(0)
|
|
elif key == ord("2"):
|
|
light_state.set_color_index(1)
|
|
elif key == ord("3"):
|
|
light_state.set_color_index(2)
|
|
elif key == ord("c") or key == ord("C"):
|
|
light_state.cycle_color()
|
|
elif key == ord("k") or key == ord("K"):
|
|
light_state.cycle_cone_size()
|
|
elif key == ord("g") or key == ord("G"):
|
|
light_state.cycle_gobo()
|
|
elif key == ord("r") or key == ord("R"):
|
|
light_state.cycle_gobo_rotation()
|
|
|
|
except KeyboardInterrupt:
|
|
print("\n[INFO] Programm durch Benutzer abgebrochen.")
|
|
finally:
|
|
print("[CLEANUP] Ressourcen freigeben...")
|
|
dmx.close()
|
|
landmarker.close()
|
|
if k4a is not None:
|
|
try:
|
|
k4a.stop()
|
|
except (RuntimeError, OSError):
|
|
pass
|
|
if cap_cv is not None:
|
|
cap_cv.release()
|
|
cv2.destroyAllWindows()
|
|
print("[CLEANUP] Erfolgreich beendet.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_light_control_test()
|