Sunday, 21 March 2021

opencv 20 motion detection


#main.py
import cv2
import numpy as np

cap = cv2.VideoCapture("assets/live cam.mp4")

_, frame1 = cap.read()
_, frame2 = cap.read()

i = 0
while cap.isOpened():
    diff = cv2.absdiff(frame1, frame2)
    gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (5, 5), 0)
    _, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
    dilated = cv2.dilate(thresh, None, iterations=3)
    contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    #cv2.drawContours(frame1, contours, -1, (0, 0, 255), 2)

    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)

        if cv2.contourArea(contour) < 2000:
            continue

        cv2.rectangle(frame1, (x, y), (x+w, y+h), (0, 0, 255), 5)

    cv2.imshow('feed', frame1)

    i += 1
    name = 'motion detection/img' + str(i) + '.jpg'

    cv2.imwrite(name, frame1)

    frame1 = frame2
    _, frame2 = cap.read()

    if cv2.waitKey(1) == ord('q'):
        break

    if cv2.waitKey(1) == ord('p'):
        # wait until any key is pressed
        cv2.waitKey(-1)

cap.release()
cv2.destroyAllWindows()

------------------------------------
#screenshot.py
import pyscreenshot as ImageGrab

for i in range(200):
    im = ImageGrab.grab(bbox=(100, 500, 1900, 1500))  # X1,Y1,X2,Y2

    name = 'screenshot/img' + str(i) + '.jpg'

    im.save(name)

reference:

screenshot
pip install pyscreenshot
pip install image

live cam

No comments:

Post a Comment