Spaces:
Sleeping
Sleeping
Commit ·
67f4ecf
0
Parent(s):
Initial commit for MotionScope Pro (Docker deployment)
Browse filesFiles changed (7)
- .gitignoreAdded+10
- DockerfileAdded+26
- README.mdAdded+77
- app.pyAdded+340
- detector.pyAdded+280
- live_run.pyAdded+70
- requirements.txtAdded+4
12345678910venv/__pycache__/*.pyc.DS_Store.envoutput.mp4output_recorded.mp4motionscope_output.mp4motionscope_snapshot.jpghand_landmarker.task1234567891011121314151617181920212223242526FROM python:3.10-slim
WORKDIR /app
# Install system dependencies for OpenCVRUN apt-get update && apt-get install -y \ libgl1-mesa-glx \ libglib2.0-0 \ wget \ && rm -rf /var/lib/apt/lists/*
# Copy requirements and install Python dependenciesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Download the MediaPipe model fileRUN wget -q -O hand_landmarker.task https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/latest/hand_landmarker.task
# Copy the application codeCOPY . .
# Expose the port Streamlit runs on (HF Spaces uses 7860)EXPOSE 7860
# Run the applicationCMD ["streamlit", "run", "app.py", "--server.port", "7860", "--server.address", "0.0.0.0"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677---title: MotionScope Proemoji: 🎥colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860app_file: app.pypinned: false---
# 🎥 MotionScope Pro — Movement Detector
A professional Streamlit application combining **MediaPipe hand tracking** and **background subtraction motion detection**.
## Features
| Feature | Description ||---|---|| 🖐️ Hand Tracking | Real-time MediaPipe hand landmark detection || 🚗 Motion Detection | Background subtraction (MOG2) with contour filtering || ⚡ Combined Mode | Both hand tracking + motion detection simultaneously || 📹 Video Upload | Upload MP4/AVI/MOV/MKV → process → download result || 📷 Webcam Snapshot | Capture a photo and process it instantly |
## How to Download & Run
### Option 1: Run on Hugging Face SpacesClick the **App** tab above to use the application directly in your browser!
### Option 2: Run Locally
1. **Clone the repository:** ```bash git clone https://huggingface.co/spaces/Jack1808/MotionScope-Pro cd MotionScope-Pro ```
2. **Create a virtual environment (recommended):** ```bash python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate ```
3. **Install dependencies:** ```bash pip install -r requirements.txt ```
4. **Run the application:** - **Web Interface:** ```bash streamlit run app.py ``` - **Real-time Webcam Window:** ```bash python live_run.py ```
1. **Sidebar** — choose detection mode and tune parameters (threshold, min area, confidence).2. **Video Upload tab** — upload a video, click **Process Video**, watch the live preview, then download the result.3. **Webcam Snapshot tab** — take a photo from your webcam and see the detected landmarks / motion overlay.
## Project Structure
```motion_detector/├── app.py # Streamlit UI├── detector.py # Core MovementDetector class├── requirements.txt # Python dependencies└── README.md # This file```
## Requirements
- Python 3.10+- A webcam (for the snapshot tab)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340"""MotionScope Pro — Streamlit front-endRun with: streamlit run app.py"""
import tempfileimport osimport cv2import numpy as npimport streamlit as stfrom detector import MovementDetector, DetectionConfig, DetectionMode
# ---------------------------------------------------------------------------# Page config# ---------------------------------------------------------------------------st.set_page_config( page_title="MotionScope Pro", page_icon="🎥", layout="wide", initial_sidebar_state="expanded",)
# ---------------------------------------------------------------------------# Custom CSS — dark, polished look# ---------------------------------------------------------------------------st.markdown( """ <style> /* ---- Global ---- */ .stApp { background: linear-gradient(135deg, #0f0c29, #302b63, #24243e); }
/* Hero header */ .hero { text-align: center; padding: 1.5rem 0 0.5rem; } .hero h1 { font-size: 2.6rem; background: linear-gradient(90deg, #00d2ff, #3a7bd5); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 0.2rem; } .hero p { color: #b0b0cc; font-size: 1.05rem; }
/* Sidebar */ section[data-testid="stSidebar"] { background: rgba(15, 12, 41, 0.95); border-right: 1px solid rgba(58, 123, 213, 0.3); }
/* Cards */ .metric-card { background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.08); border-radius: 12px; padding: 1rem 1.2rem; margin-bottom: 0.8rem; } .metric-card h3 { margin: 0 0 0.3rem; font-size: 0.95rem; color: #7eb8f7; } .metric-card .val { font-size: 1.6rem; font-weight: 700; color: #fff; }
/* Feature badges */ .badge-row { display: flex; gap: 0.6rem; flex-wrap: wrap; justify-content: center; margin-bottom: 1.2rem; } .badge { background: rgba(58, 123, 213, 0.15); border: 1px solid rgba(58, 123, 213, 0.35); border-radius: 20px; padding: 0.35rem 0.9rem; font-size: 0.82rem; color: #a0c4ff; }
/* Hide default Streamlit branding */ #MainMenu, footer, header {visibility: hidden;} </style> """, unsafe_allow_html=True,)
# ---------------------------------------------------------------------------# Hero header# ---------------------------------------------------------------------------st.markdown( """ <div class="hero"> <h1>🎥 MotionScope Pro</h1> <p>Advanced Movement Detection — Hand Tracking & Motion Analysis</p> </div> """, unsafe_allow_html=True,)
# Feature badgesst.markdown( """ <div class="badge-row"> <span class="badge">🖐️ Hand Tracking</span> <span class="badge">🚗 Motion Detection</span> <span class="badge">⚡ Combined Mode</span> <span class="badge">📹 Video Upload</span> <span class="badge">📷 Webcam Snapshots</span> </div> """, unsafe_allow_html=True,)
# ---------------------------------------------------------------------------# Sidebar — settings# ---------------------------------------------------------------------------with st.sidebar: st.markdown("## ⚙️ Detection Settings")
mode_label = st.selectbox( "Detection Mode", options=[m.value for m in DetectionMode], index=1, help="Choose what the detector should look for.", ) mode = DetectionMode(mode_label)
st.markdown("---") st.markdown("### 🔧 Motion Parameters")
motion_threshold = st.slider( "Motion threshold", min_value=50, max_value=255, value=180, step=5, help="Higher → less sensitive (ignores faint motion).", ) min_contour_area = st.slider( "Min object area (px²)", min_value=100, max_value=10000, value=1000, step=100, help="Ignore contours smaller than this area.", )
st.markdown("---") st.markdown("### 🖐️ Hand Parameters")
max_hands = st.slider("Max hands to detect", 1, 4, 2) det_confidence = st.slider( "Detection confidence", 0.1, 1.0, 0.5, 0.05, ) track_confidence = st.slider( "Tracking confidence", 0.1, 1.0, 0.5, 0.05, )
st.markdown("---") st.markdown( "<small style='color:#666'>Built with OpenCV · MediaPipe · Streamlit</small>", unsafe_allow_html=True, )
# Build config from sidebar valuesconfig = DetectionConfig( min_detection_confidence=det_confidence, min_tracking_confidence=track_confidence, max_num_hands=max_hands, motion_threshold=motion_threshold, min_contour_area=min_contour_area,)
# ---------------------------------------------------------------------------# Cached detector (rebuilt when config changes)# ---------------------------------------------------------------------------
@st.cache_resourcedef get_detector(): return MovementDetector()
detector = get_detector()detector.rebuild(config)
# ---------------------------------------------------------------------------# Tabs — Video Upload | Webcam Snapshot# ---------------------------------------------------------------------------tab_video, tab_webcam = st.tabs(["📹 Video Upload", "📷 Webcam Snapshot"])
# ======================== VIDEO UPLOAD TAB ==============================with tab_video: uploaded = st.file_uploader( "Upload a video file", type=["mp4", "avi", "mov", "mkv"], help="Supported formats: MP4, AVI, MOV, MKV", )
if uploaded is not None: # Save upload to a temp file tfile = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") tfile.write(uploaded.read()) tfile.flush() input_path = tfile.name
# Show the original video with st.expander("🎬 Original video", expanded=False): st.video(input_path)
# Process button if st.button("🚀 Process Video", type="primary", use_container_width=True): output_path = os.path.join(tempfile.gettempdir(), "motionscope_output.mp4")
progress_bar = st.progress(0, text="Processing…") frame_placeholder = st.empty() metrics_placeholder = st.empty()
total_objects = 0 frame_num = 0
try: for display_frame, result_path, progress in detector.process_video( input_path, mode=mode, output_path=output_path, ): if display_frame is not None: frame_num += 1 # Show every 4th frame for speed if frame_num % 4 == 0 or progress >= 1.0: frame_placeholder.image( display_frame, caption=f"Frame {detector.frame_count}", use_container_width=True, ) progress_bar.progress( progress, text=f"Processing… {int(progress * 100)}%", )
if result_path is not None: progress_bar.progress(1.0, text="✅ Done!")
st.success( f"Processed **{detector.frame_count}** frames successfully!" )
# Metrics row col1, col2, col3 = st.columns(3) col1.metric("Total Frames", detector.frame_count) col2.metric("Mode", mode.value) col3.metric("Status", "✅ Complete")
# Download button with open(result_path, "rb") as f: st.download_button( "⬇️ Download Processed Video", data=f, file_name="motionscope_output.mp4", mime="video/mp4", use_container_width=True, )
except Exception as e: st.error(f"❌ Error during processing: {e}") finally: # Cleanup temp input try: os.unlink(input_path) except OSError: pass else: # Empty state st.markdown( """ <div style="text-align:center; padding:3rem 0; color:#888;"> <p style="font-size:3rem; margin-bottom:0.5rem;">📹</p> <p>Upload a video above to get started</p> </div> """, unsafe_allow_html=True, )
# ======================== WEBCAM SNAPSHOT TAB ===========================with tab_webcam: st.markdown( "Take a photo with your webcam and the detector will process it instantly." )
camera_input = st.camera_input("📷 Take a photo")
if camera_input is not None: # Decode the image file_bytes = np.frombuffer(camera_input.getvalue(), dtype=np.uint8) img_bgr = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR)
if img_bgr is not None: # Flip for mirror effect img_bgr = cv2.flip(img_bgr, 1)
# Process processed_bgr = detector.process_frame(img_bgr, mode) processed_rgb = cv2.cvtColor(processed_bgr, cv2.COLOR_BGR2RGB)
col_orig, col_proc = st.columns(2) with col_orig: st.markdown("**Original**") original_rgb = cv2.cvtColor( cv2.flip(img_bgr, 1), cv2.COLOR_BGR2RGB # undo our flip for display ) st.image(original_rgb, use_container_width=True) with col_proc: st.markdown("**Processed**") st.image(processed_rgb, use_container_width=True)
# Download processed image _, buf = cv2.imencode(".jpg", processed_bgr) st.download_button( "⬇️ Download Processed Image", data=buf.tobytes(), file_name="motionscope_snapshot.jpg", mime="image/jpeg", use_container_width=True, ) else: st.error("Could not decode the captured image.") else: st.markdown( """ <div style="text-align:center; padding:3rem 0; color:#888;"> <p style="font-size:3rem; margin-bottom:0.5rem;">📷</p> <p>Click the camera button above to capture a snapshot</p> </div> """, unsafe_allow_html=True, )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280"""MotionScope Pro - Core Movement Detection EngineCombines MediaPipe HandLandmarker (tasks API) with background subtraction."""
import osimport cv2import numpy as npimport mediapipe as mpfrom enum import Enumfrom dataclasses import dataclassfrom typing import Tuple, Generator
# MediaPipe tasks API (lazy-loaded via attribute access)_BaseOptions = mp.tasks.BaseOptions_HandLandmarker = mp.tasks.vision.HandLandmarker_HandLandmarkerOptions = mp.tasks.vision.HandLandmarkerOptions_RunningMode = mp.tasks.vision.RunningMode
# Path to the hand landmarker model (shipped alongside this file)_MODEL_PATH = os.path.join(os.path.dirname(__file__), "hand_landmarker.task")
class DetectionMode(Enum): """Available detection modes.""" HAND_TRACKING = "Hand Tracking" MOTION_DETECTION = "Motion Detection" COMBINED = "Combined"
@dataclassclass DetectionConfig: """Tunable parameters for detection.""" # MediaPipe hand settings min_detection_confidence: float = 0.5 min_tracking_confidence: float = 0.5 max_num_hands: int = 2
# Motion detection settings motion_threshold: int = 180 min_contour_area: int = 1000 blur_kernel_size: Tuple[int, int] = (5, 5) morph_kernel_size: Tuple[int, int] = (3, 3)
# Background subtractor settings bg_history: int = 500 bg_var_threshold: int = 16 bg_detect_shadows: bool = True
class MovementDetector: """ Professional movement detector combining MediaPipe hands + MOG2 background subtraction. """
def __init__(self, config: DetectionConfig | None = None): self.config = config or DetectionConfig() self.hand_landmarker = self._build_hand_landmarker() self.back_sub = self._build_back_sub() self.frame_count: int = 0
# ------------------------------------------------------------------ # Builder helpers # ------------------------------------------------------------------
def _build_hand_landmarker(self): options = _HandLandmarkerOptions( base_options=_BaseOptions(model_asset_path=_MODEL_PATH), running_mode=_RunningMode.IMAGE, num_hands=self.config.max_num_hands, min_hand_detection_confidence=self.config.min_detection_confidence, min_tracking_confidence=self.config.min_tracking_confidence, ) return _HandLandmarker.create_from_options(options)
def _build_back_sub(self): return cv2.createBackgroundSubtractorMOG2( history=self.config.bg_history, varThreshold=self.config.bg_var_threshold, detectShadows=self.config.bg_detect_shadows, )
def rebuild(self, config: DetectionConfig): """Rebuild internal models when the user changes settings.""" self.config = config self.hand_landmarker.close() self.hand_landmarker = self._build_hand_landmarker() self.back_sub = self._build_back_sub() self.frame_count = 0
# ------------------------------------------------------------------ # Hand detection (new tasks API) # ------------------------------------------------------------------
def detect_hands(self, frame: np.ndarray) -> np.ndarray: """ Detect hands and draw landmarks + labels on *frame* (BGR). Uses MediaPipe tasks API HandLandmarker. """ rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
result = self.hand_landmarker.detect(mp_image)
h, w, _ = frame.shape
if result.hand_landmarks: for idx, landmarks in enumerate(result.hand_landmarks): # Draw connections manually since draw_landmarks expects # NormalizedLandmarkList but we have a list of landmarks self._draw_hand_skeleton(frame, landmarks, w, h)
# Label near wrist (landmark 0) wrist = landmarks[0] cx, cy = int(wrist.x * w), int(wrist.y * h)
label = "Hand" if result.handedness and idx < len(result.handedness): label = result.handedness[idx][0].category_name
cv2.putText( frame, label, (cx - 30, cy - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2, )
return frame
def _draw_hand_skeleton(self, frame, landmarks, w, h): """Draw landmark points and connections on *frame*.""" # Define the 21 hand landmark connections (pairs of indices) connections = [ (0, 1), (1, 2), (2, 3), (3, 4), # Thumb (0, 5), (5, 6), (6, 7), (7, 8), # Index (0, 9), (9, 10), (10, 11), (11, 12), # Middle (0, 13), (13, 14), (14, 15), (15, 16), # Ring (0, 17), (17, 18), (18, 19), (19, 20), # Pinky (5, 9), (9, 13), (13, 17), # Palm ]
# Convert normalized landmarks to pixel coordinates pts = [] for lm in landmarks: px, py = int(lm.x * w), int(lm.y * h) pts.append((px, py))
# Draw connections for start, end in connections: cv2.line(frame, pts[start], pts[end], (0, 255, 0), 2)
# Draw landmark dots for px, py in pts: cv2.circle(frame, (px, py), 5, (255, 0, 128), -1) cv2.circle(frame, (px, py), 5, (255, 255, 255), 1)
# ------------------------------------------------------------------ # Motion detection # ------------------------------------------------------------------
def detect_motion(self, frame: np.ndarray) -> Tuple[np.ndarray, np.ndarray, int]: """ Background-subtraction motion detection.
Returns ------- processed : BGR frame with bounding boxes mask : cleaned foreground mask count : number of detected moving objects """ fg_mask = self.back_sub.apply(frame)
_, mask_thresh = cv2.threshold( fg_mask, self.config.motion_threshold, 255, cv2.THRESH_BINARY, )
mask_blur = cv2.GaussianBlur(mask_thresh, self.config.blur_kernel_size, 0)
kernel = cv2.getStructuringElement( cv2.MORPH_ELLIPSE, self.config.morph_kernel_size, ) mask_clean = cv2.morphologyEx(mask_blur, cv2.MORPH_OPEN, kernel) mask_clean = cv2.morphologyEx(mask_clean, cv2.MORPH_CLOSE, kernel)
contours, _ = cv2.findContours( mask_clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE, )
valid = [] for cnt in contours: area = cv2.contourArea(cnt) if area > self.config.min_contour_area: valid.append(cnt) x, y, bw, bh = cv2.boundingRect(cnt) cv2.rectangle(frame, (x, y), (x + bw, y + bh), (0, 0, 255), 2) cv2.putText( frame, f"Area: {int(area)}", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2, )
cv2.putText( frame, f"Moving objects: {len(valid)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2, ) return frame, mask_clean, len(valid)
# ------------------------------------------------------------------ # High-level frame dispatcher # ------------------------------------------------------------------
def process_frame(self, frame: np.ndarray, mode: DetectionMode) -> np.ndarray: """Process a single frame according to the selected *mode*.""" self.frame_count += 1 out = frame.copy()
if mode == DetectionMode.HAND_TRACKING: return self.detect_hands(out) elif mode == DetectionMode.MOTION_DETECTION: processed, _, _ = self.detect_motion(out) return processed elif mode == DetectionMode.COMBINED: motion_frame, _, _ = self.detect_motion(out) return self.detect_hands(motion_frame) return out
# ------------------------------------------------------------------ # Full-video processing generator # ------------------------------------------------------------------
def process_video( self, source: str, mode: DetectionMode = DetectionMode.MOTION_DETECTION, output_path: str = "output.mp4", ) -> Generator[Tuple[np.ndarray | None, str | None, float], None, None]: """ Iterate over every frame in *source*, yield processed RGB frames.
Yields ------ (display_frame_rgb | None, output_path | None, progress) """ self.frame_count = 0 self.back_sub = self._build_back_sub() # fresh background model
cap = cv2.VideoCapture(source) if not cap.isOpened(): raise ValueError(f"Cannot open video: {source}")
frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) or 30 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 1
fourcc = cv2.VideoWriter_fourcc(*"mp4v") out = cv2.VideoWriter(output_path, fourcc, fps, (frame_w, frame_h))
try: while True: ret, frame = cap.read() if not ret: break
processed = self.process_frame(frame, mode) out.write(processed)
display = cv2.cvtColor(processed, cv2.COLOR_BGR2RGB) progress = min(self.frame_count / total_frames, 1.0) yield display, None, progress finally: cap.release() out.release() yield None, output_path, 1.0
# ------------------------------------------------------------------ # Cleanup # ------------------------------------------------------------------
def release(self): """Free resources.""" self.hand_landmarker.close()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""MotionScope Pro - Live Webcam AnalysisRun this script to see real-time updates in a new window.Usage: python live_run.py"""
import cv2import timefrom detector import MovementDetector, DetectionMode
def main(): print("Initializing...") detector = MovementDetector() # Try to open webcam cap = cv2.VideoCapture(0) if not cap.isOpened(): print("Error: Could not open webcam.") return
print("Webcam started.") print("Controls:") print(" 'q' - Quit") print(" 'm' - Switch Mode (Hand -> Motion -> Combined)")
mode = DetectionMode.MOTION_DETECTION print(f"Current Mode: {mode.value}")
try: while True: ret, frame = cap.read() if not ret: print("Failed to grab frame.") break
# Mirror effect frame = cv2.flip(frame, 1)
# Process frame processed = detector.process_frame(frame, mode)
# Draw HUD cv2.putText( processed, f"Mode: {mode.value} (Press 'm' to switch)", (10, processed.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 0), 2 )
cv2.imshow("MotionScope Pro (Live)", processed)
# Handle keys key = cv2.waitKey(1) & 0xFF if key == ord('q'): break elif key == ord('m'): # Cycle modes modes = list(DetectionMode) current_idx = modes.index(mode) next_idx = (current_idx + 1) % len(modes) mode = modes[next_idx] print(f"Switched to: {mode.value}")
finally: cap.release() cv2.destroyAllWindows() detector.release() print("Resources released.")
if __name__ == "__main__": main()1234streamlit>=1.28.0opencv-python-headless>=4.8.0mediapipe>=0.10.0numpy>=1.24.0.gitignoreAdded+10
DockerfileAdded+26
README.mdAdded+77
app.pyAdded+340
detector.pyAdded+280
live_run.pyAdded+70
requirements.txtAdded+4