MorphGuard / scripts /auto_test.py
juanquy's picture
Initial clean commit of modular MorphGuard
2978bba
Raw
History Blame Contribute Delete
2.25 kB
#!/usr/bin/env python3
"""
Auto-test script for MorphGuard demo:
- Enumerate attached webcams (up to 4)
- Capture a frame from each camera
- Send each to the /api/detect endpoint
- Send the first frame to /api/demorph
"""
try:
import cv2
except ImportError:
print("Error: OpenCV (cv2) not installed. Run 'pip install opencv-python' and retry.")
exit(1)
import requests
import time
BASE_URL = 'http://localhost:5000'
def list_and_capture_cams(max_cams=4):
caps = []
for i in range(max_cams):
cap = cv2.VideoCapture(i)
if cap.isOpened():
caps.append((i, cap))
else:
cap.release()
frames = []
for idx, cap in caps:
ret, frame = cap.read()
cap.release()
if ret:
# Encode to JPEG bytes
_, buf = cv2.imencode('.jpg', frame)
frames.append((idx, buf.tobytes()))
return frames
def detect_images(frames):
print(f"Sending {len(frames)} captured camera frames to /api/detect...")
results = []
for idx, img_bytes in frames:
resp = requests.post(f"{BASE_URL}/api/detect", files={'image': (f'cam{idx}.jpg', img_bytes)})
try:
data = resp.json()
except ValueError:
data = {'error': 'invalid json', 'status_code': resp.status_code}
print(f"Camera {idx} detect response:", data)
results.append(data)
return results
def demorph_image(frame):
idx, img_bytes = frame
print(f"Sending camera {idx} frame to /api/demorph...")
resp = requests.post(f"{BASE_URL}/api/demorph", files={'image': (f'cam{idx}.jpg', img_bytes)})
try:
data = resp.json()
except ValueError:
data = {'error': 'invalid json', 'status_code': resp.status_code}
print(f"Demorph response:", data)
return data
def main():
print("Starting auto-test of MorphGuard demo...")
# Give server a moment
time.sleep(2)
frames = list_and_capture_cams()
if not frames:
print("No webcams detected. Exiting.")
return
detect_results = detect_images(frames)
# Demorph first detected frame
demorph_data = demorph_image(frames[0])
print("Auto-test complete.")
if __name__ == '__main__':
main()