import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the video
cap = cv2.VideoCapture('../data/video/video_test.mp4')
# Extract an image from the video in order to elect region of interest (ROI) by drawing a rectangle
ret, frame = cap.read()
# Draw a rectangle on the image
cv2.rectangle(frame, (100, 100), (300, 300), (255, 0, 0), 2)
# Select the ROI
roi = frame[100:300, 100:300]
# Convert the image to grayscale
roi_gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
# Create a mask
roi_mask = np.zeros(roi_gray.shape[:2], np.uint8)
# Draw a circle on the mask
cv2.circle(roi_mask, (150, 150), 100, 255, -1)
# Apply the mask to the grayscale image
masked_roi_gray = cv2.bitwise_and(roi_gray, roi_gray, mask=roi_mask)
# Create a threshold to exclude minute movements
threshold = 70
# Apply threshold to the masked grayscale image
_, thresh = cv2.threshold(masked_roi_gray, threshold, 255, cv2.THRESH_BINARY)
# Find changes in the masked grayscale image
_, contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Draw a circle around the detected changes
for cnt in contours:
(x, y, w, h) = cv2.boundingRect(cnt)
cv2.circle(roi, (x + int(w/2), y + int(h/2)), 5, (0, 0, 255), -1)
# Show the image
cv2.imshow('image', frame)
# Wait for a key press
cv2.waitKey(0)
# Destroy all windows
cv2.destroyAllWindows()