new light test files
This commit is contained in:
1 parent
53fbca6f40
commit
1ecf3a66f3
9 files changed
+1722
-4
No files matched your search
@@ -4,5 +4,4 @@
|
|||||||
- Vor jedem Commit: `ruff check` und `ruff format`.
|
- Vor jedem Commit: `ruff check` und `ruff format`.
|
||||||
|
|
||||||
## Projektstruktur
|
## Projektstruktur
|
||||||
- Quellcode liegt unter "src/matrixmania/", Tests unter "test/test_matrixmania/"
|
-Tests unter 'Moving_Head_Test/'
|
||||||
- Testpakete, Testdateien und Testfunktionen beginnen mit "test_"
|
|
||||||
Binary file not shown.
Executable
+492
@@ -0,0 +1,492 @@
|
|||||||
|
#!/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 == "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.
|
||||||
|
"""
|
||||||
|
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()
|
||||||
+2
-2
@@ -17,5 +17,5 @@ dev = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
pythonpath = "src"
|
pythonpath = [".", "src"]
|
||||||
testpaths = ["tests"]
|
testpaths = ["test"]
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Paket für DMX-Lichtsteuerung und Kinect-Gesteninteraktion."""
|
||||||
|
|
||||||
|
from src.light_control.light_control import (
|
||||||
|
ColorOption,
|
||||||
|
ConeSizeOption,
|
||||||
|
DMXController,
|
||||||
|
GestureClassifier,
|
||||||
|
GoboOption,
|
||||||
|
GoboRotationOption,
|
||||||
|
LightState,
|
||||||
|
LowPassFilter,
|
||||||
|
NormalizedLandmark,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ColorOption",
|
||||||
|
"ConeSizeOption",
|
||||||
|
"DMXController",
|
||||||
|
"GestureClassifier",
|
||||||
|
"GoboOption",
|
||||||
|
"GoboRotationOption",
|
||||||
|
"LightState",
|
||||||
|
"LowPassFilter",
|
||||||
|
"NormalizedLandmark",
|
||||||
|
]
|
||||||
@@ -0,0 +1,492 @@
|
|||||||
|
"""Lichtsteuerung für Stairville MH-X25 Moving Head via DMX und Gestenerkennung.
|
||||||
|
|
||||||
|
Implementiert die DMX-Steuerung nach Bedienungsanleitung für:
|
||||||
|
- Feste Helligkeit (Dimmer / Shutter) mit Umschaltung AN/AUS
|
||||||
|
- Feste Pan- und Tilt-Werte
|
||||||
|
- Farbradsteuerung (3 wählbare Farben: Weiß, Rot, Blau sowie Erweiterungen)
|
||||||
|
- Gobo-Rad- und Gobo-Rotationssteuerung
|
||||||
|
- Steuerung der Kegelgröße (Spot-Kegel / Blende)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
try:
|
||||||
|
import serial
|
||||||
|
import serial.tools.list_ports
|
||||||
|
except ImportError:
|
||||||
|
serial = None
|
||||||
|
|
||||||
|
DEFAULT_COM_PORT: str = "COM3"
|
||||||
|
DMX_BAUD: int = 57600
|
||||||
|
|
||||||
|
# Feste Standard-Positionen für Pan und Tilt (Zentriert)
|
||||||
|
FIXED_PAN_VALUE: int = 128
|
||||||
|
FIXED_TILT_VALUE: int = 128
|
||||||
|
DEFAULT_FIXED_BRIGHTNESS: int = 255
|
||||||
|
|
||||||
|
|
||||||
|
class ColorOption(Enum):
|
||||||
|
"""Farben für das Farbrad des Stairville MH-X25 (Kanal 6)."""
|
||||||
|
|
||||||
|
WHITE = ("Weiß", 0)
|
||||||
|
RED = ("Rot", 37)
|
||||||
|
BLUE = ("Blau", 27)
|
||||||
|
GREEN = ("Grün", 17)
|
||||||
|
YELLOW = ("Gelb", 7)
|
||||||
|
|
||||||
|
def __init__(self, display_name: str, dmx_value: int) -> None:
|
||||||
|
"""Initialisiert eine Farboption.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
display_name: Lesbarer Name der Farbe.
|
||||||
|
dmx_value: DMX-Wert nach Bedienungsanleitung.
|
||||||
|
"""
|
||||||
|
self.display_name = display_name
|
||||||
|
self.dmx_value = dmx_value
|
||||||
|
|
||||||
|
|
||||||
|
class ConeSizeOption(Enum):
|
||||||
|
"""Kegelgrößen (Spot-Blenden) für den Moving Head."""
|
||||||
|
|
||||||
|
LARGE = ("Groß (Offen)", 0)
|
||||||
|
MEDIUM = ("Mittel (Gobo 1)", 10)
|
||||||
|
SMALL = ("Klein (Gobo 2 / Pinspot)", 18)
|
||||||
|
|
||||||
|
def __init__(self, display_name: str, dmx_value: int) -> None:
|
||||||
|
"""Initialisiert eine Kegelgrößen-Option.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
display_name: Lesbarer Name der Kegelgröße.
|
||||||
|
dmx_value: DMX-Wert auf dem Gobo-Kanal.
|
||||||
|
"""
|
||||||
|
self.display_name = display_name
|
||||||
|
self.dmx_value = dmx_value
|
||||||
|
|
||||||
|
|
||||||
|
class GoboOption(Enum):
|
||||||
|
"""Gobos auf dem Gobo-Rad des Stairville MH-X25 (Kanal 9)."""
|
||||||
|
|
||||||
|
OPEN = ("Offen", 0)
|
||||||
|
GOBO_1 = ("Gobo 1 (Kreispunkt)", 10)
|
||||||
|
GOBO_2 = ("Gobo 2 (Feiner Punkt)", 18)
|
||||||
|
GOBO_3 = ("Gobo 3 (Spirale)", 26)
|
||||||
|
GOBO_4 = ("Gobo 4 (Stern)", 34)
|
||||||
|
GOBO_5 = ("Gobo 5 (Muster)", 42)
|
||||||
|
GOBO_6 = ("Gobo 6 (Fächer)", 50)
|
||||||
|
GOBO_7 = ("Gobo 7 (Ring)", 58)
|
||||||
|
SHAKE = ("Gobo Shake", 80)
|
||||||
|
|
||||||
|
def __init__(self, display_name: str, dmx_value: int) -> None:
|
||||||
|
"""Initialisiert eine Gobo-Option.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
display_name: Lesbarer Name des Gobos.
|
||||||
|
dmx_value: DMX-Wert nach Bedienungsanleitung.
|
||||||
|
"""
|
||||||
|
self.display_name = display_name
|
||||||
|
self.dmx_value = dmx_value
|
||||||
|
|
||||||
|
|
||||||
|
class GoboRotationOption(Enum):
|
||||||
|
"""Gobo-Rotation des Stairville MH-X25 (Kanal 10)."""
|
||||||
|
|
||||||
|
STOP = ("Aus / Fixiert", 0)
|
||||||
|
SLOW_CW = ("Langsam Vorwärts", 80)
|
||||||
|
FAST_CW = ("Schnell Vorwärts", 140)
|
||||||
|
SLOW_CCW = ("Langsam Rückwärts", 160)
|
||||||
|
BOUNCE = ("Bouncing", 240)
|
||||||
|
|
||||||
|
def __init__(self, display_name: str, dmx_value: int) -> None:
|
||||||
|
"""Initialisiert eine Gobo-Rotationsoption.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
display_name: Lesbarer Name der Rotation.
|
||||||
|
dmx_value: DMX-Wert nach Bedienungsanleitung.
|
||||||
|
"""
|
||||||
|
self.display_name = display_name
|
||||||
|
self.dmx_value = dmx_value
|
||||||
|
|
||||||
|
|
||||||
|
class DMXController:
|
||||||
|
"""Verwaltet DMX512 via Enttec DMX USB Pro Protokoll mit Mock-Fallback."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self, port: str = DEFAULT_COM_PORT, baud: int = DMX_BAUD, mock: bool = False
|
||||||
|
) -> None:
|
||||||
|
"""Initialisiert den DMX-Controller.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
port: COM-Port oder Gerätedatei für das DMX-Interface.
|
||||||
|
baud: Baudrate der seriellen Verbindung.
|
||||||
|
mock: Erzwingt den Mock-Modus unabhängig von gefundener Hardware.
|
||||||
|
"""
|
||||||
|
self.port = port
|
||||||
|
self.baud = baud
|
||||||
|
self.buffer = bytearray(512)
|
||||||
|
self.mock_mode = mock or (serial is None)
|
||||||
|
self.ser: Any = None
|
||||||
|
|
||||||
|
if not self.mock_mode:
|
||||||
|
self._connect()
|
||||||
|
|
||||||
|
def _connect(self) -> None:
|
||||||
|
"""Stellt die serielle Verbindung zum DMX-Interface her."""
|
||||||
|
if serial is None:
|
||||||
|
self.mock_mode = True
|
||||||
|
return
|
||||||
|
|
||||||
|
available_ports = [p.device for p in serial.tools.list_ports.comports()]
|
||||||
|
target_port: str | None = None
|
||||||
|
|
||||||
|
if self.port in available_ports:
|
||||||
|
target_port = self.port
|
||||||
|
elif available_ports:
|
||||||
|
target_port = available_ports[0]
|
||||||
|
|
||||||
|
if target_port:
|
||||||
|
try:
|
||||||
|
self.ser = serial.Serial(
|
||||||
|
target_port, baudrate=self.baud, timeout=0.1, write_timeout=0.1
|
||||||
|
)
|
||||||
|
self.port = target_port
|
||||||
|
print(f"[DMX] Verbunden mit DMX-Interface an {self.port}")
|
||||||
|
return
|
||||||
|
except (serial.SerialException, PermissionError, OSError) as err:
|
||||||
|
print(f"[DMX] Fehler beim Öffnen von {target_port}: {err}")
|
||||||
|
|
||||||
|
self.mock_mode = True
|
||||||
|
print("[DMX] Kein DMX-Interface gefunden. Mock-Modus aktiviert.")
|
||||||
|
|
||||||
|
def set_channel(self, channel: int, value: int) -> None:
|
||||||
|
"""Setzt den Wert eines DMX-Kanals (1-512, 0-255).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
channel: DMX-Kanalnummer (1-512).
|
||||||
|
value: Auszugebender Helligkeits-/Steuerwert (0-255).
|
||||||
|
"""
|
||||||
|
if 1 <= channel <= 512:
|
||||||
|
self.buffer[channel - 1] = max(0, min(255, int(value)))
|
||||||
|
|
||||||
|
def get_channel(self, channel: int) -> int:
|
||||||
|
"""Gibt den aktuellen Wert eines DMX-Kanals zurück.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
channel: DMX-Kanalnummer (1-512).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Aktueller Kanalwert (0-255).
|
||||||
|
"""
|
||||||
|
if 1 <= channel <= 512:
|
||||||
|
return self.buffer[channel - 1]
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def send(self) -> None:
|
||||||
|
"""Sendet den DMX-Frame via Enttec USB Pro Protokoll."""
|
||||||
|
if self.mock_mode or not self.ser or not self.ser.is_open:
|
||||||
|
return
|
||||||
|
|
||||||
|
packet = (
|
||||||
|
bytearray([0x7E, 6, 513 & 0xFF, (513 >> 8) & 0xFF, 0x00])
|
||||||
|
+ self.buffer
|
||||||
|
+ bytearray([0xE7])
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
self.ser.write(packet)
|
||||||
|
except (serial.SerialException, serial.SerialTimeoutException, OSError):
|
||||||
|
print("[DMX] Übertragungsfehler. Wechsle in Mock-Modus.")
|
||||||
|
self.mock_mode = True
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
"""Schaltet den Scheinwerfer aus und schließt die Schnittstelle."""
|
||||||
|
# Dimmer auf 0 und Shutter schließen
|
||||||
|
self.set_channel(7, 0)
|
||||||
|
self.set_channel(8, 0)
|
||||||
|
self.send()
|
||||||
|
if self.ser and hasattr(self.ser, "is_open") and self.ser.is_open:
|
||||||
|
try:
|
||||||
|
self.ser.close()
|
||||||
|
except (OSError, serial.SerialException) as err:
|
||||||
|
print(f"[DMX] Fehler beim Schließen der seriellen Schnittstelle: {err}")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LightState:
|
||||||
|
"""Zustandsklasse für die Lichtsteuerung des Moving Heads."""
|
||||||
|
|
||||||
|
light_on: bool = True
|
||||||
|
fixed_brightness: int = DEFAULT_FIXED_BRIGHTNESS
|
||||||
|
pan: int = FIXED_PAN_VALUE
|
||||||
|
tilt: int = FIXED_TILT_VALUE
|
||||||
|
color: ColorOption = ColorOption.WHITE
|
||||||
|
gobo: GoboOption = GoboOption.OPEN
|
||||||
|
cone_size: ConeSizeOption = ConeSizeOption.LARGE
|
||||||
|
gobo_rotation: GoboRotationOption = GoboRotationOption.STOP
|
||||||
|
shutter_open: bool = True
|
||||||
|
|
||||||
|
def toggle_light(self) -> bool:
|
||||||
|
"""Schaltet das Licht ein oder aus.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Neuer Status (True = An, False = Aus).
|
||||||
|
"""
|
||||||
|
self.light_on = not self.light_on
|
||||||
|
return self.light_on
|
||||||
|
|
||||||
|
def set_color_index(self, index: int) -> ColorOption:
|
||||||
|
"""Wählt eine der drei Primärfarben (0: Weiß, 1: Rot, 2: Blau).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
index: Farbindex (0 = Weiß, 1 = Rot, 2 = Blau).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Ausgewählte Farboption.
|
||||||
|
"""
|
||||||
|
primary_colors = [ColorOption.WHITE, ColorOption.RED, ColorOption.BLUE]
|
||||||
|
self.color = primary_colors[index % len(primary_colors)]
|
||||||
|
return self.color
|
||||||
|
|
||||||
|
def cycle_color(self) -> ColorOption:
|
||||||
|
"""Wechselt zyklisch zwischen den 3 Hauptfarben (Weiß, Rot, Blau).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Neu gewählte Farboption.
|
||||||
|
"""
|
||||||
|
primary_colors = [ColorOption.WHITE, ColorOption.RED, ColorOption.BLUE]
|
||||||
|
current_idx = (
|
||||||
|
primary_colors.index(self.color) if self.color in primary_colors else -1
|
||||||
|
)
|
||||||
|
next_idx = (current_idx + 1) % len(primary_colors)
|
||||||
|
self.color = primary_colors[next_idx]
|
||||||
|
return self.color
|
||||||
|
|
||||||
|
def cycle_cone_size(self) -> ConeSizeOption:
|
||||||
|
"""Wechselt zyklisch durch die verfügbaren Kegelgrößen.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Neu gewählte Kegelgröße.
|
||||||
|
"""
|
||||||
|
sizes = list(ConeSizeOption)
|
||||||
|
current_idx = sizes.index(self.cone_size)
|
||||||
|
self.cone_size = sizes[(current_idx + 1) % len(sizes)]
|
||||||
|
return self.cone_size
|
||||||
|
|
||||||
|
def cycle_gobo(self) -> GoboOption:
|
||||||
|
"""Wechselt zyklisch durch die Gobo-Muster.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Neu gewähltes Gobo.
|
||||||
|
"""
|
||||||
|
gobos = list(GoboOption)
|
||||||
|
current_idx = gobos.index(self.gobo)
|
||||||
|
self.gobo = gobos[(current_idx + 1) % len(gobos)]
|
||||||
|
return self.gobo
|
||||||
|
|
||||||
|
def cycle_gobo_rotation(self) -> GoboRotationOption:
|
||||||
|
"""Wechselt zyklisch durch die Rotationsmodi des Gobos.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Neu gewählter Rotationsmodus.
|
||||||
|
"""
|
||||||
|
rotations = list(GoboRotationOption)
|
||||||
|
current_idx = rotations.index(self.gobo_rotation)
|
||||||
|
self.gobo_rotation = rotations[(current_idx + 1) % len(rotations)]
|
||||||
|
return self.gobo_rotation
|
||||||
|
|
||||||
|
def apply_to_dmx(self, dmx: DMXController) -> None:
|
||||||
|
"""Überträgt den aktuellen Zustand auf die DMX-Kanäle (12-Kanal-Modus).
|
||||||
|
|
||||||
|
Kanalbelegung Stairville MH-X25 (12-Kanal):
|
||||||
|
- CH 1: Pan (fester Wert)
|
||||||
|
- CH 2: Pan fine (0)
|
||||||
|
- CH 3: Tilt (fester Wert)
|
||||||
|
- CH 4: Tilt fine (0)
|
||||||
|
- CH 5: Pan/Tilt Speed (0 = maximal schnell)
|
||||||
|
- CH 6: Farbrad (0-127 Farbpositionen)
|
||||||
|
- CH 7: Shutter / Strobe (0=Zu, 4-7=Offen)
|
||||||
|
- CH 8: Dimmer (0-255 Helligkeit)
|
||||||
|
- CH 9: Gobo-Rad (0=Offen, 8-71 Gobos, usw.)
|
||||||
|
- CH 10: Gobo-Rotation (0=Stop, 64-147 Vorwärts, 154-237 Rückwärts)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
dmx: Ziel-DMXController-Instanz.
|
||||||
|
"""
|
||||||
|
# CH 1 & 2: Pan fest
|
||||||
|
dmx.set_channel(1, self.pan)
|
||||||
|
dmx.set_channel(2, self.tilt) # Tilt fest
|
||||||
|
|
||||||
|
# CH 5: Speed
|
||||||
|
dmx.set_channel(5, 0)
|
||||||
|
|
||||||
|
# CH 6: Farbrad
|
||||||
|
dmx.set_channel(6, self.color.dmx_value)
|
||||||
|
|
||||||
|
# CH 7 & 8: Shutter & Dimmer
|
||||||
|
if self.light_on:
|
||||||
|
dmx.set_channel(7, 4) # Shutter offen (Wert 4 nach Anleitung)
|
||||||
|
dmx.set_channel(8, self.fixed_brightness)
|
||||||
|
else:
|
||||||
|
dmx.set_channel(7, 0) # Shutter geschlossen
|
||||||
|
dmx.set_channel(8, 0) # Dimmer aus
|
||||||
|
|
||||||
|
# CH 9: Gobo-Auswahl / Kegelgröße
|
||||||
|
# Falls Kegelgröße nicht 'LARGE' (offen) ist, bestimmt die Kegelgröße den Gobowert
|
||||||
|
if self.cone_size != ConeSizeOption.LARGE:
|
||||||
|
dmx.set_channel(9, self.cone_size.dmx_value)
|
||||||
|
else:
|
||||||
|
dmx.set_channel(9, self.gobo.dmx_value)
|
||||||
|
|
||||||
|
# CH 10: Gobo-Rotation
|
||||||
|
dmx.set_channel(10, self.gobo_rotation.dmx_value)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class NormalizedLandmark:
|
||||||
|
"""Repräsentation eines normalisierten 2D/3D-Landmarks."""
|
||||||
|
|
||||||
|
x: float
|
||||||
|
y: float
|
||||||
|
z: float = 0.0
|
||||||
|
visibility: float = 1.0
|
||||||
|
|
||||||
|
|
||||||
|
class GestureClassifier:
|
||||||
|
"""Klassifiziert Benutzergesten aus MediaPipe Pose Landmarks."""
|
||||||
|
|
||||||
|
# Landmark Indizes
|
||||||
|
IDX_NOSE = 0
|
||||||
|
IDX_LEFT_SHOULDER = 11
|
||||||
|
IDX_RIGHT_SHOULDER = 12
|
||||||
|
IDX_LEFT_ELBOW = 13
|
||||||
|
IDX_RIGHT_ELBOW = 14
|
||||||
|
IDX_LEFT_WRIST = 15
|
||||||
|
IDX_RIGHT_WRIST = 16
|
||||||
|
IDX_LEFT_HIP = 23
|
||||||
|
IDX_RIGHT_HIP = 24
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def classify_light_toggle(
|
||||||
|
cls, landmarks: list[NormalizedLandmark] | list[Any]
|
||||||
|
) -> bool | None:
|
||||||
|
"""Klassifiziert das Ein- bzw. Ausschalten des Lichts über den rechten Arm.
|
||||||
|
|
||||||
|
Gestenlogik:
|
||||||
|
- Hand deutlich über Schulter -> Licht AN (True)
|
||||||
|
- Hand deutlich unter Hüfte -> Licht AUS (False)
|
||||||
|
- Dazwischen -> Keine Statusänderung (None)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
landmarks: Liste der 33 Pose-Landmarks.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True für AN, False für AUS, None für neutrale Haltung.
|
||||||
|
"""
|
||||||
|
if len(landmarks) <= cls.IDX_RIGHT_HIP:
|
||||||
|
return None
|
||||||
|
|
||||||
|
r_wrist = landmarks[cls.IDX_RIGHT_WRIST]
|
||||||
|
r_shoulder = landmarks[cls.IDX_RIGHT_SHOULDER]
|
||||||
|
r_hip = landmarks[cls.IDX_RIGHT_HIP]
|
||||||
|
|
||||||
|
# In Bildkoordinaten ist Y oben = 0, unten = 1
|
||||||
|
if r_wrist.y < r_shoulder.y - 0.05:
|
||||||
|
return True
|
||||||
|
if r_wrist.y > r_hip.y + 0.05:
|
||||||
|
return False
|
||||||
|
return None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def classify_color(
|
||||||
|
cls, landmarks: list[NormalizedLandmark] | list[Any]
|
||||||
|
) -> ColorOption | None:
|
||||||
|
"""Klassifiziert die Farbwahl (3 Farben) über die Höhe der linken Hand.
|
||||||
|
|
||||||
|
- Linke Hand unter Hüfte -> Weiß (Standard)
|
||||||
|
- Linke Hand zwischen Hüfte und Schulter (Brusthöhe) -> Rot
|
||||||
|
- Linke Hand über Schulterhöhe -> Blau
|
||||||
|
|
||||||
|
Args:
|
||||||
|
landmarks: Liste der 33 Pose-Landmarks.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Ausgewählte ColorOption oder None.
|
||||||
|
"""
|
||||||
|
if len(landmarks) <= cls.IDX_LEFT_HIP:
|
||||||
|
return None
|
||||||
|
|
||||||
|
l_wrist = landmarks[cls.IDX_LEFT_WRIST]
|
||||||
|
l_shoulder = landmarks[cls.IDX_LEFT_SHOULDER]
|
||||||
|
l_hip = landmarks[cls.IDX_LEFT_HIP]
|
||||||
|
|
||||||
|
if l_wrist.y > l_hip.y:
|
||||||
|
return ColorOption.WHITE
|
||||||
|
if l_wrist.y > l_shoulder.y:
|
||||||
|
return ColorOption.RED
|
||||||
|
return ColorOption.BLUE
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def classify_cone_size(
|
||||||
|
cls, landmarks: list[NormalizedLandmark] | list[Any]
|
||||||
|
) -> ConeSizeOption | None:
|
||||||
|
"""Klassifiziert die Spot-Kegelgröße anhand des horizontalen Handabstands.
|
||||||
|
|
||||||
|
- Hände sehr weit auseinander (> 0.50) -> Groß (LARGE)
|
||||||
|
- Mittlerer Abstand (0.25 - 0.50) -> Mittel (MEDIUM)
|
||||||
|
- Hände eng zusammen (< 0.25) -> Klein / Pinspot (SMALL)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
landmarks: Liste der Pose-Landmarks.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Kegelgrößen-Option oder None.
|
||||||
|
"""
|
||||||
|
if len(landmarks) <= cls.IDX_RIGHT_WRIST:
|
||||||
|
return None
|
||||||
|
|
||||||
|
l_wrist = landmarks[cls.IDX_LEFT_WRIST]
|
||||||
|
r_wrist = landmarks[cls.IDX_RIGHT_WRIST]
|
||||||
|
|
||||||
|
dx = abs(l_wrist.x - r_wrist.x)
|
||||||
|
dy = abs(l_wrist.y - r_wrist.y)
|
||||||
|
dist = (dx**2 + dy**2) ** 0.5
|
||||||
|
|
||||||
|
if dist > 0.45:
|
||||||
|
return ConeSizeOption.LARGE
|
||||||
|
if dist > 0.22:
|
||||||
|
return ConeSizeOption.MEDIUM
|
||||||
|
return ConeSizeOption.SMALL
|
||||||
|
|
||||||
|
|
||||||
|
class LowPassFilter:
|
||||||
|
"""Tiefpassfilter (Exponential Moving Average) zur Glättung."""
|
||||||
|
|
||||||
|
def __init__(self, alpha: float = 0.25) -> None:
|
||||||
|
"""Initialisiert den Filter.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
alpha: Glättungsfaktor (0.0 = träge, 1.0 = ungefiltert).
|
||||||
|
"""
|
||||||
|
self.alpha = alpha
|
||||||
|
self.val: float | None = None
|
||||||
|
|
||||||
|
def update(self, new_val: float) -> float:
|
||||||
|
"""Aktualisiert den Filter mit einem neuen Wert.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
new_val: Neuer Messwert.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Gefilterter Wert.
|
||||||
|
"""
|
||||||
|
if self.val is None:
|
||||||
|
self.val = float(new_val)
|
||||||
|
else:
|
||||||
|
self.val = self.alpha * float(new_val) + (1.0 - self.alpha) * self.val
|
||||||
|
return self.val
|
||||||
|
|
||||||
|
def reset(self) -> None:
|
||||||
|
"""Setzt den internen Filterzustand zurück."""
|
||||||
|
self.val = None
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Testpaket für die Lichtsteuerung."""
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
"""Unit-Tests für die Lichtsteuerungslogik und DMX-Schnittstelle."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from src.light_control.light_control import (
|
||||||
|
ColorOption,
|
||||||
|
ConeSizeOption,
|
||||||
|
DMXController,
|
||||||
|
GestureClassifier,
|
||||||
|
GoboOption,
|
||||||
|
GoboRotationOption,
|
||||||
|
LightState,
|
||||||
|
LowPassFilter,
|
||||||
|
NormalizedLandmark,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_dmx_controller_buffer_operations() -> None:
|
||||||
|
"""Testet das Setzen und Auslesen von DMX-Kanälen im Mock-Modus."""
|
||||||
|
dmx = DMXController(mock=True)
|
||||||
|
assert dmx.mock_mode is True
|
||||||
|
|
||||||
|
dmx.set_channel(1, 128)
|
||||||
|
dmx.set_channel(2, 255)
|
||||||
|
dmx.set_channel(8, 0)
|
||||||
|
dmx.set_channel(512, 42)
|
||||||
|
|
||||||
|
assert dmx.get_channel(1) == 128
|
||||||
|
assert dmx.get_channel(2) == 255
|
||||||
|
assert dmx.get_channel(8) == 0
|
||||||
|
assert dmx.get_channel(512) == 42
|
||||||
|
assert dmx.get_channel(0) == 0
|
||||||
|
assert dmx.get_channel(513) == 0
|
||||||
|
|
||||||
|
# Wertebereichsbegrenzung
|
||||||
|
dmx.set_channel(10, 300)
|
||||||
|
assert dmx.get_channel(10) == 255
|
||||||
|
dmx.set_channel(11, -50)
|
||||||
|
assert dmx.get_channel(11) == 0
|
||||||
|
|
||||||
|
# Senden und Schließen im Mock-Modus
|
||||||
|
dmx.send()
|
||||||
|
dmx.close()
|
||||||
|
assert dmx.get_channel(7) == 0
|
||||||
|
assert dmx.get_channel(8) == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_light_state_initial_and_dmx_mapping() -> None:
|
||||||
|
"""Testet den Anfangszustand und die DMX-Kanalzuordnung."""
|
||||||
|
state = LightState()
|
||||||
|
dmx = DMXController(mock=True)
|
||||||
|
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
|
||||||
|
# Gemäß Bedienungsanleitung
|
||||||
|
assert dmx.get_channel(1) == 128 # Pan fest
|
||||||
|
assert dmx.get_channel(2) == 128 # Tilt fest
|
||||||
|
assert dmx.get_channel(6) == ColorOption.WHITE.dmx_value # Farbrad Weiß
|
||||||
|
assert dmx.get_channel(7) == 4 # Shutter offen
|
||||||
|
assert dmx.get_channel(8) == 255 # Dimmer voll
|
||||||
|
assert dmx.get_channel(9) == 0 # Gobo offen / Großer Kegel
|
||||||
|
assert dmx.get_channel(10) == 0 # Gobo Rotation Stop
|
||||||
|
|
||||||
|
|
||||||
|
def test_light_state_toggle_brightness() -> None:
|
||||||
|
"""Testet das Ein- und Ausschalten der festen Helligkeit."""
|
||||||
|
state = LightState(fixed_brightness=200, light_on=True)
|
||||||
|
dmx = DMXController(mock=True)
|
||||||
|
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(8) == 200
|
||||||
|
assert dmx.get_channel(7) == 4
|
||||||
|
|
||||||
|
# Ausschalten
|
||||||
|
new_status = state.toggle_light()
|
||||||
|
assert new_status is False
|
||||||
|
assert state.light_on is False
|
||||||
|
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(8) == 0
|
||||||
|
assert dmx.get_channel(7) == 0
|
||||||
|
|
||||||
|
# Wiedereinschalten
|
||||||
|
state.toggle_light()
|
||||||
|
assert state.light_on is True
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(8) == 200
|
||||||
|
assert dmx.get_channel(7) == 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_light_state_color_switching() -> None:
|
||||||
|
"""Testet die Umschaltung zwischen 3 Farben (Weiß, Rot, Blau)."""
|
||||||
|
state = LightState()
|
||||||
|
dmx = DMXController(mock=True)
|
||||||
|
|
||||||
|
# 1. Farbe: Weiß
|
||||||
|
state.set_color_index(0)
|
||||||
|
assert state.color == ColorOption.WHITE
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(6) == 0
|
||||||
|
|
||||||
|
# 2. Farbe: Rot
|
||||||
|
state.set_color_index(1)
|
||||||
|
assert state.color == ColorOption.RED
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(6) == 37
|
||||||
|
|
||||||
|
# 3. Farbe: Blau
|
||||||
|
state.set_color_index(2)
|
||||||
|
assert state.color == ColorOption.BLUE
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(6) == 27
|
||||||
|
|
||||||
|
# Zyklischer Wechsel
|
||||||
|
state.cycle_color()
|
||||||
|
assert state.color == ColorOption.WHITE
|
||||||
|
|
||||||
|
|
||||||
|
def test_light_state_cone_size_and_gobo() -> None:
|
||||||
|
"""Testet die Steuerung von Kegelgröße und Gobo-Rad."""
|
||||||
|
state = LightState()
|
||||||
|
dmx = DMXController(mock=True)
|
||||||
|
|
||||||
|
# Kegelgröße umschalten
|
||||||
|
state.cycle_cone_size()
|
||||||
|
assert state.cone_size == ConeSizeOption.MEDIUM
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(9) == 10
|
||||||
|
|
||||||
|
state.cycle_cone_size()
|
||||||
|
assert state.cone_size == ConeSizeOption.SMALL
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(9) == 18
|
||||||
|
|
||||||
|
# Gobo-Auswahl (bei Standard-Kegelgröße)
|
||||||
|
state.cone_size = ConeSizeOption.LARGE
|
||||||
|
state.gobo = GoboOption.GOBO_4
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(9) == 34
|
||||||
|
|
||||||
|
# Gobo-Rotation
|
||||||
|
state.cycle_gobo_rotation()
|
||||||
|
assert state.gobo_rotation == GoboRotationOption.SLOW_CW
|
||||||
|
state.apply_to_dmx(dmx)
|
||||||
|
assert dmx.get_channel(10) == 80
|
||||||
|
|
||||||
|
|
||||||
|
def test_gesture_classifier_light_toggle() -> None:
|
||||||
|
"""Testet die Erkennung der Licht-Ein/Aus-Geste mit dem rechten Arm."""
|
||||||
|
# 33 Dummy-Landmarks erzeugen
|
||||||
|
landmarks = [NormalizedLandmark(x=0.5, y=0.5) for _ in range(33)]
|
||||||
|
|
||||||
|
# Schulter bei y=0.3, Hüfte bei y=0.6
|
||||||
|
landmarks[12] = NormalizedLandmark(x=0.6, y=0.3) # Rechte Schulter
|
||||||
|
landmarks[24] = NormalizedLandmark(x=0.6, y=0.6) # Rechte Hüfte
|
||||||
|
|
||||||
|
# Hand über Schulter (y=0.1) -> Licht AN
|
||||||
|
landmarks[16] = NormalizedLandmark(x=0.6, y=0.1) # Rechtes Handgelenk
|
||||||
|
assert GestureClassifier.classify_light_toggle(landmarks) is True
|
||||||
|
|
||||||
|
# Hand unter Hüfte (y=0.8) -> Licht AUS
|
||||||
|
landmarks[16] = NormalizedLandmark(x=0.6, y=0.8)
|
||||||
|
assert GestureClassifier.classify_light_toggle(landmarks) is False
|
||||||
|
|
||||||
|
# Hand auf mittlerer Höhe -> Keine Änderung (None)
|
||||||
|
landmarks[16] = NormalizedLandmark(x=0.6, y=0.45)
|
||||||
|
assert GestureClassifier.classify_light_toggle(landmarks) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_gesture_classifier_color() -> None:
|
||||||
|
"""Testet die Farberkennung anhand der Höhe der linken Hand."""
|
||||||
|
landmarks = [NormalizedLandmark(x=0.5, y=0.5) for _ in range(33)]
|
||||||
|
|
||||||
|
landmarks[11] = NormalizedLandmark(x=0.4, y=0.3) # Linke Schulter
|
||||||
|
landmarks[23] = NormalizedLandmark(x=0.4, y=0.6) # Linke Hüfte
|
||||||
|
|
||||||
|
# Hand unter Hüfte -> Weiß
|
||||||
|
landmarks[15] = NormalizedLandmark(x=0.4, y=0.8)
|
||||||
|
assert GestureClassifier.classify_color(landmarks) == ColorOption.WHITE
|
||||||
|
|
||||||
|
# Hand auf Brusthöhe -> Rot
|
||||||
|
landmarks[15] = NormalizedLandmark(x=0.4, y=0.45)
|
||||||
|
assert GestureClassifier.classify_color(landmarks) == ColorOption.RED
|
||||||
|
|
||||||
|
# Hand über Schulter -> Blau
|
||||||
|
landmarks[15] = NormalizedLandmark(x=0.4, y=0.1)
|
||||||
|
assert GestureClassifier.classify_color(landmarks) == ColorOption.BLUE
|
||||||
|
|
||||||
|
|
||||||
|
def test_gesture_classifier_cone_size() -> None:
|
||||||
|
"""Testet die Kegelgrößenerkennung anhand des Handabstands."""
|
||||||
|
landmarks = [NormalizedLandmark(x=0.5, y=0.5) for _ in range(33)]
|
||||||
|
|
||||||
|
# Weit auseinander (Distanz = 0.6) -> Groß
|
||||||
|
landmarks[15] = NormalizedLandmark(x=0.2, y=0.4)
|
||||||
|
landmarks[16] = NormalizedLandmark(x=0.8, y=0.4)
|
||||||
|
assert GestureClassifier.classify_cone_size(landmarks) == ConeSizeOption.LARGE
|
||||||
|
|
||||||
|
# Mittlerer Abstand (Distanz = 0.35) -> Mittel
|
||||||
|
landmarks[15] = NormalizedLandmark(x=0.35, y=0.4)
|
||||||
|
landmarks[16] = NormalizedLandmark(x=0.70, y=0.4)
|
||||||
|
assert GestureClassifier.classify_cone_size(landmarks) == ConeSizeOption.MEDIUM
|
||||||
|
|
||||||
|
# Eng zusammen (Distanz = 0.15) -> Klein
|
||||||
|
landmarks[15] = NormalizedLandmark(x=0.45, y=0.4)
|
||||||
|
landmarks[16] = NormalizedLandmark(x=0.60, y=0.4)
|
||||||
|
assert GestureClassifier.classify_cone_size(landmarks) == ConeSizeOption.SMALL
|
||||||
|
|
||||||
|
|
||||||
|
def test_low_pass_filter() -> None:
|
||||||
|
"""Testet das Glättungsverhalten des Tiefpassfilters."""
|
||||||
|
filt = LowPassFilter(alpha=0.5)
|
||||||
|
assert filt.val is None
|
||||||
|
|
||||||
|
v1 = filt.update(100.0)
|
||||||
|
assert v1 == pytest.approx(100.0)
|
||||||
|
|
||||||
|
v2 = filt.update(200.0)
|
||||||
|
assert v2 == pytest.approx(150.0)
|
||||||
|
|
||||||
|
filt.reset()
|
||||||
|
assert filt.val is None
|
||||||
Executable
+485
@@ -0,0 +1,485 @@
|
|||||||
|
#!/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()
|
||||||
Reference in new issue
Block a user