Skip to content

Instantly share code, notes, and snippets.

@mike-huls
Last active December 14, 2022 10:37
Show Gist options
  • Save mike-huls/110d9e1850364793e18d739ef6c6742c to your computer and use it in GitHub Desktop.
Save mike-huls/110d9e1850364793e18d739ef6c6742c to your computer and use it in GitHub Desktop.
import time
import cv2
import numpy as np
from PIL import ImageGrab
def intruder_detector():
screenTOP = 210
screenBOT = 775
screenLFT = 150
screenRGT = 1275
framecount = 0
strt_time = time.time()
comparison_frame = None
movement_detected = False
contours = []
while True:
framecount += 1
movement_detected = False
img_bgr= np.array(ImageGrab.grab(bbox=(screenLFT, screenTOP, screenRGT, screenBOT)))
# 2
img_rgb = cv2.cvtColor(src=img_bgr, code=cv2.COLOR_BGR2RGB)
processed_frame = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
processed_frame = cv2.GaussianBlur(processed_frame, (5, 5), 0)
if (comparison_frame is None or time.time() - strt_time > 10):
comparison_frame = processed_frame
strt_time = time.time()
# calculate difference
diff_frame = cv2.absdiff(src1=comparison_frame, src2=processed_frame)
thresh_frame = cv2.threshold(src=diff_frame, thresh=20, maxval=255, type=cv2.THRESH_BINARY)[1]
contours, _ = cv2.findContours(image=thresh_frame, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
# 4. Draw green rectangles around each contour on the original frame and show
for contour in contours:
if cv2.contourArea(contour) < 250:
# too small: skip!
continue
(x, y, w, h) = cv2.boundingRect(contour)
# making green rectangle around the moving object
cv2.rectangle(img_rgb, (x, y), (x + w, y + h), (0, 255, 0), 3)
movement_detected = True
if (movement_detected):
cv2.putText(img=img_rgb, text=f"Movement detected!", org=(75, 20), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.7, color=(0, 0, 255), thickness=2);
# Display
cv2.imshow('Result', img_rgb)
# press ESCAPE to exit
if (cv2.waitKey(30) == 27):
break
if (__name__ == '__main__'):
intruder_detector()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment