new tilt test file

This commit is contained in:
kuehnleinma103760 committed 2026-11-04 16:13:36 +01:00
1 parent 58ffd2da0e
commit 9ed5128df0
1 file changed
+585
+585
View File
@@ -0,0 +1,585 @@
#!/usr/bin/env python3
"""
Isoliertes Testskript für TILT-Steuerung (Stairville MH-X25) mit Azure Kinect DK.
Trackt ausschließlich die rechte Hand (vertikale Bewegung -> Tilt).
Pan bleibt fest auf der Mittelposition (128).
"""
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.25
FIXED_PAN = 128 # Pan bleibt fest zentriert
DEFAULT_TILT = 128 # Startwert für Tilt (Mitte)
# Physikalischer Versatz des Moving Heads relativ zur Kinect-Linse (in Metern)
# Kinect-Koordinaten: +X = rechts, +Y = nach unten, +Z = nach vorne
OFFSET_X = 0.00
OFFSET_Z = 0.00
OFFSET_Y_STANDING = 0.25 # Scheinwerfer 0,25 m unter der Kinect
OFFSET_Y_CEILING = -0.25 # Scheinwerfer 0,25 m über der Kinect
TILT_RANGE_DEG = 270.0
IDX_RIGHT_WRIST = 16 # Nur rechte Hand
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-Modell bei Bedarf 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 (MIT KANAL-MODUS-UMSCHALTUNG 12CH / 6CH)
# ------------------------------------------------------------------------------
class DMXController:
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.mode_12ch = True # True = 12-Kanal-Modus (Tilt=CH3), False = 6-Kanal-Modus (Tilt=CH2)
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 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(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 alle Kanäle passend zum gewählten Modus (12ch oder 6ch)."""
self.buffer = bytearray(512)
if self.mode_12ch:
# 12-Kanal-Modus: CH1=Pan, CH2=PanFine, CH3=Tilt, CH4=TiltFine, CH5=Speed, CH6=Color, CH7=Gobo, CH8=Dimmer, CH9=Shutter
self.set_channel(1, FIXED_PAN)
self.set_channel(2, 0)
self.set_channel(3, DEFAULT_TILT)
self.set_channel(4, 0)
self.set_channel(5, 0) # Speed max
self.set_channel(6, 0) # Weiß
self.set_channel(7, 0) # Gobo offen
self.set_channel(8, 255) # Dimmer 100%
self.set_channel(9, 3) # Shutter offen
else:
# 6-Kanal-Modus: CH1=Pan, CH2=Tilt, CH3=Color, CH4=Gobo, CH5=Shutter, CH6=Dimmer
self.set_channel(1, FIXED_PAN)
self.set_channel(2, DEFAULT_TILT)
self.set_channel(3, 0) # Weiß
self.set_channel(4, 0) # Gobo offen
self.set_channel(5, 3) # Shutter offen
self.set_channel(6, 255) # Dimmer 100%
self.send()
def set_tilt(self, tilt_val: int) -> None:
"""Schreibt den Tilt-Wert auf den für den Modus zuständigen DMX-Kanal."""
tilt_ch = 3 if self.mode_12ch else 2
self.set_channel(tilt_ch, tilt_val)
def get_tilt(self) -> int:
tilt_ch = 3 if self.mode_12ch else 2
return self.get_channel(tilt_ch)
@property
def tilt_channel_num(self) -> int:
return 3 if self.mode_12ch else 2
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] Übertragungsfehler. Wechsle in Mock-Modus.")
self.mock_mode = True
def close(self) -> None:
if self.mode_12ch:
self.set_channel(8, 0)
self.set_channel(9, 0)
else:
self.set_channel(5, 0)
self.set_channel(6, 0)
self.send()
if self.ser and self.ser.is_open:
try:
self.ser.close()
print("[DMX] Verbindung getrennt.")
except Exception:
pass
# ------------------------------------------------------------------------------
# 3. FILTER & TILT-MATHEMATIK
# ------------------------------------------------------------------------------
class LowPassFilter:
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_tilt(
x_m: float, y_m: float, z_m: float, ceiling_mode: bool = False
) -> tuple[int, float]:
"""
Berechnet den Tilt-DMX-Wert (0-255) sowie den Winkel in Grad.
Kinect: +Y ist unten, -Y ist oben.
"""
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)
# -dy, damit Hand nach oben (-Y) einen positiven Winkel (+Grad) ergibt
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)))), tilt_deg
def extract_right_hand_3d(
landmark,
image_width: int,
image_height: int,
depth_aligned: np.ndarray,
k4a: PyK4A,
) -> tuple[float, float, float, int, int] | None:
"""
Ermittelt die 3D-Position der rechten Hand mit einem robusten 5x5-Pixel-Fenster,
damit Randpixel am Handgelenk nicht ins Leere (Hintergrund) messen.
"""
u = int(landmark.x * image_width)
v = int(landmark.y * image_height)
if 2 <= u < (image_width - 2) and 2 <= v < (image_height - 2):
# 5x5 Patch um das Handgelenk ausschneiden und gültige Tiefenwerte (350-5000 mm) filtern
patch = depth_aligned[v - 2 : v + 3, u - 2 : u + 3]
valid_depths = patch[(patch > 350) & (patch < 5000)]
if valid_depths.size > 0:
# Kleinsten/nächsten Median-Tiefenwert der Hand nehmen (verhindert Messung der Rückwand)
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,
)
x_m = float(pt_3d[0]) / 1000.0
y_m = float(pt_3d[1]) / 1000.0
z_m = float(pt_3d[2]) / 1000.0
return x_m, y_m, z_m, u, v
return None
# ------------------------------------------------------------------------------
# 4. HAUPTPROGRAMM
# ------------------------------------------------------------------------------
def main() -> None:
print("=" * 70)
print("ISOLIERTER TILT-TEST (NUR RECHTE HAND) - STAIRVILLE MH-X25")
print("=" * 70)
k4a = None
landmarker = None
dmx = None
try:
# 1. MediaPipe laden
print("[INIT] Lade MediaPipe PoseLandmarker (Full)...")
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. Kinect 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 starten
dmx = DMXController()
filter_tilt = LowPassFilter()
filter_tilt.reset(DEFAULT_TILT)
tracking_enabled = True
ceiling_mode = False
prev_time = time.time()
current_angle_deg = 0.0
print("\n[STEUERUNG IM FENSTER]")
print(" Rechte Hand heben/senken -> Steuert TILT")
print(" 'r' oder 'c' -> Reset auf Tilt 128 & Tracking PAUSIEREN")
print(" 'Leertaste' -> Tracking EIN / AUS")
print(" 'w' / 's' -> Manuell Tilt +10 / -10 (pausiert Tracking)")
print(" 'k' -> DMX-Kanalmodus wechseln (12-Kanal CH3 <-> 6-Kanal CH2)")
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)
hand_status = "Tracking pausiert (Manuell / Reset)"
if tracking_enabled:
hand_status = "Rechte Hand: Nicht erkannt"
if (
detection_result.pose_landmarks
and len(detection_result.pose_landmarks) > 0
):
landmarks = detection_result.pose_landmarks[0]
right_wrist = landmarks[IDX_RIGHT_WRIST]
right_3d = extract_right_hand_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, current_angle_deg = 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)
hand_status = (
f"Hand 3D: Y={ry_m:+.2f}m | Z={rz_m:+.2f}m "
f"({current_angle_deg:+.1f} Grad)"
)
# Zielkreis auf rechter Hand zeichnen
cv2.circle(color_bgr, (ru, rv), 12, (0, 200, 255), -1)
cv2.circle(color_bgr, (ru, rv), 14, (255, 255, 255), 2)
cv2.putText(
color_bgr,
f"TILT: {tilt_val}",
(ru + 16, rv + 5),
cv2.FONT_HERSHEY_SIMPLEX,
0.6,
(0, 200, 255),
2,
)
else:
hand_status = "Rechte Hand: Keine gueltige Tiefe (0.35m - 5.0m)"
# DMX-Paket 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, 235), (20, 20, 20), -1)
color_bgr = cv2.addWeighted(overlay, 0.78, color_bgr, 0.22, 0)
# 1. Tracking-Status
trk_color = (0, 255, 0) if tracking_enabled else (0, 140, 255)
trk_text = (
"STATUS: TRACKING AKTIV (RECHTE HAND)"
if tracking_enabled
else "STATUS: PAUSIERT (HALT / MANUELL)"
)
cv2.putText(
color_bgr, trk_text, (20, 35), cv2.FONT_HERSHEY_SIMPLEX, 0.55, trk_color, 2
)
cv2.putText(
color_bgr,
f"FPS: {fps:4.1f}",
(480, 35),
cv2.FONT_HERSHEY_SIMPLEX,
0.50,
(255, 255, 255),
1,
)
# 2. DMX-Status & Aktueller Tilt-Kanal
dmx_mode_str = "12-Kanal (Tilt=CH3)" if dmx.mode_12ch else "6-Kanal (Tilt=CH2)"
conn_str = "MOCK" if dmx.mock_mode else dmx.port
cv2.putText(
color_bgr,
f"DMX ({conn_str}) | Modus: {dmx_mode_str} | Montage: {'DECKE' if ceiling_mode else 'BODEN'}",
(20, 62),
cv2.FONT_HERSHEY_SIMPLEX,
0.45,
(200, 200, 200),
1,
)
# 3. Großer Tilt-Wert + Visueller Balken
tilt_cur = dmx.get_tilt()
cv2.putText(
color_bgr,
f"TILT (CH {dmx.tilt_channel_num}): {tilt_cur:3d} / 255 (Pan fix: {FIXED_PAN})",
(20, 95),
cv2.FONT_HERSHEY_SIMPLEX,
0.60,
(0, 255, 255),
2,
)
# Fortschrittsbalken für Tilt (0 bis 255)
bar_x, bar_y, bar_w, bar_h = 20, 108, 540, 14
cv2.rectangle(
color_bgr, (bar_x, bar_y), (bar_x + bar_w, bar_y + bar_h), (60, 60, 60), -1
)
fill_w = int((tilt_cur / 255.0) * bar_w)
cv2.rectangle(
color_bgr, (bar_x, bar_y), (bar_x + fill_w, bar_y + bar_h), (0, 200, 255), -1
)
# Mittelmarkierung bei 128
mid_x = bar_x + int((128.0 / 255.0) * bar_w)
cv2.line(
color_bgr, (mid_x, bar_y - 3), (mid_x, bar_y + bar_h + 3), (255, 255, 255), 2
)
# 4. Hand-Koordinaten
cv2.putText(
color_bgr,
hand_status,
(20, 145),
cv2.FONT_HERSHEY_SIMPLEX,
0.48,
(180, 255, 180),
1,
)
# 5. Tasten-Legende
cv2.line(color_bgr, (20, 160), (560, 160), (80, 80, 80), 1)
cv2.putText(
color_bgr,
"[r / c] Reset (128) & Pause | [Space] Tracking Weiter/Pause",
(20, 180),
cv2.FONT_HERSHEY_SIMPLEX,
0.42,
(220, 220, 220),
1,
)
cv2.putText(
color_bgr,
"[w / s] Manuell Tilt +10/-10 | [k] 12ch/6ch Modus wechseln",
(20, 200),
cv2.FONT_HERSHEY_SIMPLEX,
0.42,
(220, 220, 220),
1,
)
cv2.putText(
color_bgr,
"[m] Boden/Decke umkehren | [q / ESC] Programm beenden",
(20, 220),
cv2.FONT_HERSHEY_SIMPLEX,
0.42,
(160, 200, 255),
1,
)
cv2.imshow("MH-X25 - Isolierter TILT Test (Rechte Hand)", color_bgr)
# --- TASTATUR-ABFRAGE ---
key = cv2.waitKey(1) & 0xFF
if key in (ord("q"), 27):
break
elif key in (ord("r"), ord("c")):
tracking_enabled = False
dmx.set_tilt(DEFAULT_TILT)
dmx.send()
filter_tilt.reset(DEFAULT_TILT)
print(f"[RESET] Tilt auf {DEFAULT_TILT} zentriert. Tracking ist PAUSIERT (Drücke Space zum Fortsetzen).")
elif key == ord(" "):
tracking_enabled = not tracking_enabled
filter_tilt.reset(dmx.get_tilt())
print(f"[STATUS] Tracking {'AKTIVIERT' if tracking_enabled else 'PAUSIERT'}.")
elif key == ord("w"):
tracking_enabled = False
new_val = min(255, dmx.get_tilt() + 10)
dmx.set_tilt(new_val)
dmx.send()
filter_tilt.reset(new_val)
print(f"[MANUELL] Tilt (CH {dmx.tilt_channel_num}) erhöht auf: {new_val}")
elif key == ord("s"):
tracking_enabled = False
new_val = max(0, dmx.get_tilt() - 10)
dmx.set_tilt(new_val)
dmx.send()
filter_tilt.reset(new_val)
print(f"[MANUELL] Tilt (CH {dmx.tilt_channel_num}) verringert auf: {new_val}")
elif key == ord("k"):
dmx.mode_12ch = not dmx.mode_12ch
dmx.init_mh_x25()
filter_tilt.reset(DEFAULT_TILT)
mode_name = "12-Kanal (Tilt=CH3)" if dmx.mode_12ch else "6-Kanal (Tilt=CH2)"
print(f"[DMX-MODUS] Gewechselt auf: {mode_name}")
elif key == ord("m"):
ceiling_mode = not ceiling_mode
filter_tilt.reset(dmx.get_tilt())
print(f"[MONTAGE] Gewechselt auf: {'DECKE' if ceiling_mode else 'BODEN/STATIV'}")
except KeyboardInterrupt:
print("\n[INFO] Abbruch durch Benutzer.")
finally:
print("[CLEANUP] Fahre Ressourcen herunter...")
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()