webcam working

This commit is contained in:
Siwat Sirichai 2025-02-24 14:21:43 +07:00
parent e1da9a6dca
commit 7911245ff9
2 changed files with 30 additions and 10 deletions

View file

@ -1,22 +1,32 @@
#!/usr/bin/python3
import argparse
import os
import cv2
import time
import logging
import shutil
import threading # added threading
from siwatsystem.pympta import load_pipeline_from_zip, run_pipeline
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s")
# Global variables for frame sharing
global_frame = None
global_ret = False
capture_running = False
def video_capture_loop(cap):
global global_frame, global_ret, capture_running
while capture_running:
global_ret, global_frame = cap.read()
time.sleep(0.01) # slight delay to reduce CPU usage
def clear_cache(cache_dir: str):
if os.path.exists(cache_dir):
shutil.rmtree(cache_dir)
os.makedirs(cache_dir, exist_ok=True)
def main(mpta_file: str, video_source: str):
global capture_running
CACHE_DIR = os.path.join(".", ".mptacache")
clear_cache(CACHE_DIR)
logging.info(f"Loading pipeline from local file: {mpta_file}")
@ -30,13 +40,19 @@ def main(mpta_file: str, video_source: str):
logging.error(f"Cannot open video source {video_source}")
return
# Start video capture in a separate thread
capture_running = True
capture_thread = threading.Thread(target=video_capture_loop, args=(cap,))
capture_thread.start()
logging.info("Press 'q' to exit.")
try:
while True:
ret, frame = cap.read()
if not ret:
logging.error("Failed to capture frame.")
break
# Use the global frame and ret updated by the thread
if not global_ret or global_frame is None:
continue # wait until a frame is available
frame = global_frame # local copy to work with
detection, bbox = run_pipeline(frame, model_tree, return_bbox=True)
if bbox:
@ -50,9 +66,11 @@ def main(mpta_file: str, video_source: str):
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
# Stop capture thread and cleanup
capture_running = False
capture_thread.join()
cap.release()
cv2.destroyAllWindows()
# Clear cache on shutdown
clear_cache(CACHE_DIR)
logging.info("Cleaned up .mptacache directory on shutdown.")

View file

@ -106,7 +106,8 @@ def run_pipeline(frame, node: dict, return_bbox: bool = False):
best_box = box_cpu
bbox = None
if detection and node.get("crop", False) and best_box is not None:
# Modified bounding box calculation: always compute bbox if best_box exists
if detection and best_box is not None:
coords = best_box.xyxy[0]
x1, y1, x2, y2 = map(int, coords)
h, w = frame.shape[:2]
@ -114,7 +115,8 @@ def run_pipeline(frame, node: dict, return_bbox: bool = False):
x2, y2 = min(w, x2), min(h, y2)
if x2 > x1 and y2 > y1:
bbox = (x1, y1, x2, y2)
frame = frame[y1:y2, x1:x2]
if node.get("crop", False):
frame = frame[y1:y2, x1:x2]
if detection is not None:
for branch in node["branches"]: