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 argparse
import os import os
import cv2 import cv2
import time import time
import logging import logging
import shutil import shutil
import threading # added threading
from siwatsystem.pympta import load_pipeline_from_zip, run_pipeline from siwatsystem.pympta import load_pipeline_from_zip, run_pipeline
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(message)s") 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): def clear_cache(cache_dir: str):
if os.path.exists(cache_dir): if os.path.exists(cache_dir):
shutil.rmtree(cache_dir) shutil.rmtree(cache_dir)
os.makedirs(cache_dir, exist_ok=True)
def main(mpta_file: str, video_source: str): def main(mpta_file: str, video_source: str):
global capture_running
CACHE_DIR = os.path.join(".", ".mptacache") CACHE_DIR = os.path.join(".", ".mptacache")
clear_cache(CACHE_DIR) clear_cache(CACHE_DIR)
logging.info(f"Loading pipeline from local file: {mpta_file}") 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}") logging.error(f"Cannot open video source {video_source}")
return 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.") logging.info("Press 'q' to exit.")
try: try:
while True: while True:
ret, frame = cap.read() # Use the global frame and ret updated by the thread
if not ret: if not global_ret or global_frame is None:
logging.error("Failed to capture frame.") continue # wait until a frame is available
break
frame = global_frame # local copy to work with
detection, bbox = run_pipeline(frame, model_tree, return_bbox=True) detection, bbox = run_pipeline(frame, model_tree, return_bbox=True)
if bbox: if bbox:
@ -50,9 +66,11 @@ def main(mpta_file: str, video_source: str):
if cv2.waitKey(1) & 0xFF == ord('q'): if cv2.waitKey(1) & 0xFF == ord('q'):
break break
finally: finally:
# Stop capture thread and cleanup
capture_running = False
capture_thread.join()
cap.release() cap.release()
cv2.destroyAllWindows() cv2.destroyAllWindows()
# Clear cache on shutdown
clear_cache(CACHE_DIR) clear_cache(CACHE_DIR)
logging.info("Cleaned up .mptacache directory on shutdown.") 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 best_box = box_cpu
bbox = None 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] coords = best_box.xyxy[0]
x1, y1, x2, y2 = map(int, coords) x1, y1, x2, y2 = map(int, coords)
h, w = frame.shape[:2] 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) x2, y2 = min(w, x2), min(h, y2)
if x2 > x1 and y2 > y1: if x2 > x1 and y2 > y1:
bbox = (x1, y1, x2, y2) 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: if detection is not None:
for branch in node["branches"]: for branch in node["branches"]: