|
| 1 | +import cv2 |
| 2 | +import time |
| 3 | +import imutils |
| 4 | + |
| 5 | +cam = cv2.VideoCapture(0) |
| 6 | +time.sleep(0) |
| 7 | +firstFrame = None |
| 8 | +area = 500 |
| 9 | +frameUpdateInterval = 100 |
| 10 | +frameCount = 0 |
| 11 | + |
| 12 | +while True: |
| 13 | + ret, img = cam.read() |
| 14 | + if not ret: |
| 15 | + break |
| 16 | + |
| 17 | + text = "Normal" |
| 18 | + img = imutils.resize(img, width=600) |
| 19 | + grayImg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) |
| 20 | + gaussianImg = cv2.GaussianBlur(grayImg, (21, 21), 0) |
| 21 | + |
| 22 | + if firstFrame is None or frameCount % frameUpdateInterval == 0: |
| 23 | + firstFrame = gaussianImg |
| 24 | + frameCount = 0 |
| 25 | + |
| 26 | + frameCount += 1 |
| 27 | + |
| 28 | + imgDiff = cv2.absdiff(firstFrame, gaussianImg) |
| 29 | + |
| 30 | + threshImg = cv2.threshold(imgDiff, 25, 255, cv2.THRESH_BINARY)[1] |
| 31 | + threshImg = cv2.dilate(threshImg, None, iterations=2) |
| 32 | + |
| 33 | + cnts = cv2.findContours(threshImg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) |
| 34 | + cnts = imutils.grab_contours(cnts) |
| 35 | + |
| 36 | + for c in cnts: |
| 37 | + if cv2.contourArea(c) < area: |
| 38 | + continue |
| 39 | + |
| 40 | + (x, y, w, h) = cv2.boundingRect(c) |
| 41 | + cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) |
| 42 | + text = "Moving Object detected" |
| 43 | + |
| 44 | + cv2.putText(img, text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) |
| 45 | + cv2.imshow("cameraFeed", img) |
| 46 | + |
| 47 | + key = cv2.waitKey(1) & 0xFF |
| 48 | + if key == ord("q"): |
| 49 | + break |
| 50 | + |
| 51 | +cam.release() |
| 52 | +cv2.destroyAllWindows() |
0 commit comments