test moving head with both hands

This commit is contained in:
lindingerlu99122 committed 2026-11-04 16:52:32 +01:00
1 parent 75c91caa70
commit c33628c230
1 file changed
+474
+474
View File
@@ -0,0 +1,474 @@
#!/usr/bin/env python3
"""
Kombiniertes Steuerungs-Skript für Azure Kinect DK & Stairville MH-X25 Moving Head.
12-Kanal-Betrieb:
- Linke Hand -> PAN (Channel 1)
- Rechte Hand -> TILT (Channel 2)
- Channel 3/4 -> Pan/Tilt Fine (auf 0 gesetzt)
- Channel 5 -> Speed (0 = maximal)
- Channel 8/9 -> Dimmer (255) / Shutter (3 = offen)
"""
import math
import os
import sys
import time
import urllib.request
import cv2
import mediapipe as mp
import numpy as np
import serial
import serial.tools.list_ports
from mediapipe.tasks import python as mp_python
from mediapipe.tasks.python import vision as mp_vision
from pyk4a import CalibrationType, ColorResolution, Config, DepthMode, PyK4A
# ------------------------------------------------------------------------------
# 0. WINDOWS DLL-PFAD ABSICHERN (Azure Kinect SDK)
# ------------------------------------------------------------------------------
_dll_handles = []
if sys.platform == "win32":
possible_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_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:
_dll_handles.append(os.add_dll_directory(kinect_bin_path))
except OSError as e:
print(f"[WARNUNG] Konnte DLL-Verzeichnis nicht registrieren: {e}")
break
# ------------------------------------------------------------------------------
# 1. KONFIGURATION & PARAMETER
# ------------------------------------------------------------------------------
DEFAULT_COM_PORT = "COM3"
DMX_BAUD = 57600
FILTER_ALPHA = 0.20 # Glättungsfaktor
# Default Zentrierungswerte (Mitte)
DEFAULT_PAN = 127
DEFAULT_TILT = 40
# Versatz des Moving Heads relativ zur Kinect-Linse (in Metern)
OFFSET_X = 0.00
OFFSET_Z = 0.00
OFFSET_Y_STANDING = 0.25 # Scheinwerfer unter der Kinect
OFFSET_Y_CEILING = -0.25 # Scheinwerfer über der Kinect
# Winkelbereiche für Moving Head
PAN_RANGE_DEG = 540.0
TILT_RANGE_DEG = 270.0
# MediaPipe Handgelenk Indizes
IDX_LEFT_WRIST = 15 # Linke Hand -> Pan
IDX_RIGHT_WRIST = 16 # Rechte Hand -> Tilt
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 Task Modell herunter."""
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] Lade Modell {filename} herunter...")
temp_path = model_path + ".download"
try:
urllib.request.urlretrieve(url, temp_path)
os.replace(temp_path, model_path)
print(f"[INIT] Download abgeschlossen: {model_path}")
except Exception as e:
if os.path.exists(temp_path):
os.remove(temp_path)
print(f"[FEHLER] Modell-Download fehlgeschlagen: {e}")
raise
return model_path
# ------------------------------------------------------------------------------
# 2. DMX-CONTROLLER (12-KANAL-MODUS: CH1=PAN, CH2=TILT)
# ------------------------------------------------------------------------------
class DMXController:
"""Steuert Enttec USB Pro DMX für 12-Kanal Betrieb."""
def __init__(self, port: str = DEFAULT_COM_PORT, baud: int = DMX_BAUD) -> None:
self.port = port
self.baud = baud
self.buffer = bytearray(512)
self.mock_mode = False
self.ser = None
self._connect()
self.init_mh_x25()
def _connect(self) -> None:
ports_info = list(serial.tools.list_ports.comports())
available_ports = [p.device for p in ports_info]
target_port = None
if self.port in available_ports:
target_port = self.port
else:
for p in ports_info:
desc = (p.description or "").upper()
mfg = (p.manufacturer or "").upper()
if "FTDI" in mfg or "USB" in desc or "DMX" in desc:
target_port = p.device
break
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] Port {target_port} konnte nicht geöffnet werden: {err}")
self.mock_mode = True
print(f"[DMX] Kein Interface gefunden (Ports: {available_ports}). MOCK-MODUS AKTIV.")
def set_channel(self, channel: int, value: int) -> None:
if 1 <= channel <= 512:
self.buffer[channel - 1] = max(0, min(255, int(round(value))))
def get_channel(self, channel: int) -> int:
if 1 <= channel <= 512:
return self.buffer[channel - 1]
return 0
def init_mh_x25(self) -> None:
"""Initialisiert DMX-Kanäle für den 12-Kanal Modus (CH1=PAN, CH2=TILT)."""
self.buffer = bytearray(512)
self.set_channel(1, DEFAULT_PAN) # CH 1: Pan
self.set_channel(2, DEFAULT_TILT) # CH 2: Tilt (wie angefordert auf Channel 2)
self.set_channel(3, 0) # CH 3: Pan Fine
self.set_channel(4, 0) # CH 4: Tilt Fine
self.set_channel(5, 0) # CH 5: Speed (0 = schnellstmöglich)
self.set_channel(6, 0) # CH 6: Farbrad (Weiß)
self.set_channel(7, 0) # CH 7: Gobo (Offen)
self.set_channel(8, 255) # CH 8: Dimmer (100%)
self.set_channel(9, 3) # CH 9: Shutter (Offen)
self.send()
def set_pan(self, val: int) -> None:
self.set_channel(1, val)
def set_tilt(self, val: int) -> None:
self.set_channel(2, val) # Belegt Channel 2 für Tilt im 12-Kanal Modus
def send(self) -> None:
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] Verbindungsabbruch. Wechsle in Mock-Modus.")
self.mock_mode = True
def close(self) -> None:
self.set_channel(8, 0) # Dimmer aus
self.set_channel(9, 0) # Shutter zu
self.send()
if self.ser and self.ser.is_open:
try:
self.ser.close()
print("[DMX] Verbindung getrennt.")
except Exception:
pass
# ------------------------------------------------------------------------------
# 3. BERECHNUNG & BILDVERARBEITUNG
# ------------------------------------------------------------------------------
class LowPassFilter:
"""Tiefpassfilter zur Unterdrückung von Messrauschen."""
def __init__(self, alpha: float = FILTER_ALPHA) -> None:
self.alpha = alpha
self.val: float | None = None
def update(self, new_val: float) -> float:
if self.val is None:
self.val = float(new_val)
else:
self.val = (1.0 - self.alpha) * self.val + self.alpha * float(new_val)
return self.val
def reset(self, val: float | None = None) -> None:
self.val = val if val is None else float(val)
def calculate_pan(x_m: float, z_m: float, ceiling_mode: bool = False) -> int:
"""Berechnet Pan-Wert (0-255) basierend auf X- und Z-Position der linken Hand."""
dx = x_m - OFFSET_X
dz = max(0.20, z_m - OFFSET_Z)
pan_rad = math.atan2(dx, dz)
pan_deg = math.degrees(pan_rad)
pan_dmx = 127.5 + (pan_deg / (PAN_RANGE_DEG / 2.0)) * 127.5
if ceiling_mode:
pan_dmx = 255.0 - pan_dmx
return int(round(max(0.0, min(255.0, pan_dmx))))
def calculate_tilt(x_m: float, y_m: float, z_m: float, ceiling_mode: bool = False) -> int:
"""Berechnet Tilt-Wert (0-255) basierend auf Y- und Z-Position der rechten Hand."""
offset_y = OFFSET_Y_CEILING if ceiling_mode else OFFSET_Y_STANDING
dx = x_m - OFFSET_X
dy = y_m - offset_y
dz = max(0.20, z_m - OFFSET_Z)
dist_horiz = math.hypot(dx, dz)
tilt_rad = math.atan2(-dy, dist_horiz)
tilt_deg = math.degrees(tilt_rad)
tilt_dmx = 127.5 + (tilt_deg / (TILT_RANGE_DEG / 2.0)) * 127.5
if ceiling_mode:
tilt_dmx = 255.0 - tilt_dmx
return int(round(max(0.0, min(255.0, tilt_dmx))))
def extract_wrist_3d(
landmark,
image_width: int,
image_height: int,
depth_aligned: np.ndarray,
k4a: PyK4A,
) -> tuple[float, float, float, int, int] | None:
"""Extrahiert robuste 3D-Koordinaten eines Handgelenks über ein 5x5 Patch-Fenster."""
u = int(landmark.x * image_width)
v = int(landmark.y * image_height)
if 2 <= u < (image_width - 2) and 2 <= v < (image_height - 2):
patch = depth_aligned[v - 2 : v + 3, u - 2 : u + 3]
valid_depths = patch[(patch > 350) & (patch < 5000)]
if valid_depths.size > 0:
z_mm = float(np.median(valid_depths))
pt_3d = k4a.calibration.convert_2d_to_3d(
coordinates=(u, v),
depth=z_mm,
source_camera=CalibrationType.COLOR,
target_camera=CalibrationType.COLOR,
)
return (
float(pt_3d[0]) / 1000.0,
float(pt_3d[1]) / 1000.0,
float(pt_3d[2]) / 1000.0,
u,
v,
)
return None
# ------------------------------------------------------------------------------
# 4. HAUPTPROGRAMM
# ------------------------------------------------------------------------------
def main() -> None:
print("=" * 70)
print("AZURE KINECT - PAN (LINKE HAND / CH1) & TILT (RECHTE HAND / CH2)")
print("STAIRVILLE MH-X25 (12-KANAL BETRIEB)")
print("=" * 70)
k4a = None
landmarker = None
dmx = None
try:
# 1. MediaPipe vorbereiten
print("[INIT] Lade 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)
# 2. Azure Kinect DK Kamera starten
print("[INIT] Starte Azure Kinect DK...")
k4a = PyK4A(
Config(
color_resolution=ColorResolution.RES_720P,
depth_mode=DepthMode.NFOV_UNBINNED,
synchronized_images_only=True,
)
)
k4a.start()
print("[INIT] Azure Kinect betriebsbereit.")
# 3. DMX & Filter initialisieren
dmx = DMXController()
filter_pan = LowPassFilter()
filter_tilt = LowPassFilter()
filter_pan.reset(DEFAULT_PAN)
filter_tilt.reset(DEFAULT_TILT)
tracking_enabled = True
ceiling_mode = False
prev_time = time.time()
print("\n[STEUERUNG UND BEDIENUNG]")
print(" Linke Hand -> Steuert PAN (Channel 1)")
print(" Rechte Hand -> Steuert TILT (Channel 2)")
print(" 'r' / 'c' -> Zentrieren auf Default (127, 127)")
print(" 'Space' -> Tracking PAUSIEREN / FORTSETZEN")
print(" 'm' -> Montage wechseln (Boden <-> Decke)")
print(" 'q' / ESC -> Beenden\n")
while True:
capture = k4a.get_capture()
if capture.color is None or capture.depth is None:
continue
depth_aligned = capture.transformed_depth
if depth_aligned is None:
continue
color_bgr = cv2.cvtColor(capture.color, cv2.COLOR_BGRA2BGR)
color_rgb = cv2.cvtColor(color_bgr, cv2.COLOR_BGR2RGB)
h, w, _ = color_bgr.shape
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=color_rgb)
detection_result = landmarker.detect(mp_image)
left_status = "L (Pan): Pausiert" if not tracking_enabled else "L (Pan): Nicht erkannt"
right_status = "R (Tilt): Pausiert" if not tracking_enabled else "R (Tilt): Nicht erkannt"
if tracking_enabled and detection_result.pose_landmarks and len(detection_result.pose_landmarks) > 0:
landmarks = detection_result.pose_landmarks[0]
# --- 1. Linke Hand -> PAN (CH 1) ---
left_wrist = landmarks[IDX_LEFT_WRIST]
left_3d = extract_wrist_3d(left_wrist, w, h, depth_aligned, k4a)
if left_3d is not None:
lx_m, _ly_m, lz_m, lu, lv = left_3d
raw_pan = calculate_pan(lx_m, lz_m, ceiling_mode=ceiling_mode)
pan_val = int(round(filter_pan.update(raw_pan)))
dmx.set_pan(pan_val)
left_status = f"L (Pan): X={lx_m:+.2f}m | Z={lz_m:+.2f}m"
cv2.circle(color_bgr, (lu, lv), 10, (0, 255, 0), -1)
cv2.putText(color_bgr, "Pan (L)", (lu + 12, lv - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# --- 2. Rechte Hand -> TILT (CH 2) ---
right_wrist = landmarks[IDX_RIGHT_WRIST]
right_3d = extract_wrist_3d(right_wrist, w, h, depth_aligned, k4a)
if right_3d is not None:
rx_m, ry_m, rz_m, ru, rv = right_3d
raw_tilt = calculate_tilt(rx_m, ry_m, rz_m, ceiling_mode=ceiling_mode)
tilt_val = int(round(filter_tilt.update(raw_tilt)))
dmx.set_tilt(tilt_val)
right_status = f"R (Tilt): Y={ry_m:+.2f}m | Z={rz_m:+.2f}m"
cv2.circle(color_bgr, (ru, rv), 10, (0, 200, 255), -1)
cv2.putText(color_bgr, "Tilt (R)", (ru + 12, rv - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 200, 255), 2)
# DMX-Signal senden
dmx.send()
# --- HUD OVERLAY ---
now = time.time()
fps = 1.0 / (now - prev_time) if (now - prev_time) > 0 else 0.0
prev_time = now
overlay = color_bgr.copy()
cv2.rectangle(overlay, (10, 10), (580, 190), (20, 20, 20), -1)
color_bgr = cv2.addWeighted(overlay, 0.78, color_bgr, 0.22, 0)
# Zeile 1: Status & FPS
status_text = "TRACKING AKTIV" if tracking_enabled else "TRACKING PAUSIERT"
status_color = (0, 255, 0) if tracking_enabled else (0, 140, 255)
cv2.putText(color_bgr, f"STATUS: {status_text}", (20, 32), cv2.FONT_HERSHEY_SIMPLEX, 0.55, status_color, 2)
cv2.putText(color_bgr, f"FPS: {fps:4.1f}", (480, 32), cv2.FONT_HERSHEY_SIMPLEX, 0.50, (255, 255, 255), 1)
# Zeile 2: Port & Montage
conn_str = "MOCK" if dmx.mock_mode else dmx.port
mount_str = "DECKE / HAENGEND" if ceiling_mode else "STATIV / BODEN"
cv2.putText(color_bgr, f"DMX Port: {conn_str} | Montage: {mount_str}", (20, 58), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1)
# Zeile 3 & 4: Status der Hände
cv2.putText(color_bgr, left_status, (20, 84), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (180, 255, 180), 1)
cv2.putText(color_bgr, right_status, (20, 108), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (180, 220, 255), 1)
# Zeile 5: Aktuelle DMX Kanäle
pan_cur = dmx.get_channel(1)
tilt_cur = dmx.get_channel(2)
cv2.putText(color_bgr, f"DMX: PAN (CH1) = {pan_cur:3d} | TILT (CH2) = {tilt_cur:3d}", (20, 136), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 255, 255), 2)
# Zeile 6: Tasten-Steuerung
cv2.putText(color_bgr, "[r / c] Reset (Zentrieren) | [Space] Pause/Start | [m] Montage | [q] Ende", (20, 170), cv2.FONT_HERSHEY_SIMPLEX, 0.40, (180, 180, 180), 1)
cv2.imshow("Azure Kinect - Moving Light Control (12CH)", color_bgr)
# --- TASTATURBEDIENUNG ---
key = cv2.waitKey(1) & 0xFF
if key in (ord("q"), 27):
break
elif key in (ord("r"), ord("c")):
dmx.init_mh_x25()
filter_pan.reset(DEFAULT_PAN)
filter_tilt.reset(DEFAULT_TILT)
print(f"[RESET] Pan ({DEFAULT_PAN}) und Tilt ({DEFAULT_TILT}) zentriert.")
elif key == ord(" "):
tracking_enabled = not tracking_enabled
filter_pan.reset(dmx.get_channel(1))
filter_tilt.reset(dmx.get_channel(2))
print(f"[STATUS] Tracking {'AKTIV' if tracking_enabled else 'PAUSIERT'}.")
elif key == ord("m"):
ceiling_mode = not ceiling_mode
filter_pan.reset(dmx.get_channel(1))
filter_tilt.reset(dmx.get_channel(2))
print(f"[MONTAGE] Gewechselt auf: {'DECKE' if ceiling_mode else 'STATIV / BODEN'}")
except KeyboardInterrupt:
print("\n[INFO] Programm abgebrochen.")
finally:
print("[CLEANUP] Schließe Ressourcen...")
if dmx is not None:
dmx.close()
if landmarker is not None:
landmarker.close()
if k4a is not None:
try:
k4a.stop()
except Exception:
pass
cv2.destroyAllWindows()
print("[CLEANUP] Beendet.")
if __name__ == "__main__":
main()