import cv2
import torch
import numpy as np
from ImageProcessing import MSCN
from torchvision.io import read_image

# Create a background subtractor object
bg_subtractor = cv2.bgsegm.createBackgroundSubtractorGMG()
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(1,10))

# Open video file or capture device
video = cv2.VideoCapture('spring_-_38344 (Original).mp4')

# Minimum and maximum area thresholds for filtering objects
min_area = 1  # Adjust as needed
max_area = 500  # Adjust as needed

frame_count = 0
while True:
    # Read frame from video
    ret, frame = video.read()
    if not ret:
        break

    # Apply background subtraction
    fg_mask = bg_subtractor.apply(frame)
    fg_mask = cv2.morphologyEx(fg_mask, cv2.MORPH_OPEN, kernel)

    # Apply thresholding to get binary foreground mask
    thresh = cv2.threshold(fg_mask, 128, 255, cv2.THRESH_BINARY)[1]

    # Find contours of the moving objects
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Filter objects by size
    for contour in contours:
        # Calculate contour area
        area = cv2.contourArea(contour)

        # Check if contour area is within the specified range
        if min_area < area < max_area :
            (x, y, w, h) = cv2.boundingRect(contour)
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # Display the resulting frame

    if frame_count > 120 :
        cv2.imshow('Moving Object Detection', frame)
        # cv2.imshow('movingobjectcontour', fg_mask)
    # Exit if 'q' is pressed
    frame_count += 1
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture and close windows
video.release()
cv2.destroyAllWindows()
