Created
October 22, 2017 09:54
-
-
Save Sulter/e395bd84298ff938c5e9414f66740a65 to your computer and use it in GitHub Desktop.
simple CV based detection for raspberry pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# import the necessary packages | |
import argparse | |
import datetime | |
import time | |
import cv2 | |
from picamera.array import PiRGBArray | |
from picamera import PiCamera | |
# construct the argument parser and parse the arguments | |
ap = argparse.ArgumentParser() | |
ap.add_argument("-a", "--min-area", type=int, default = 200, help="minimum area size") | |
ap.add_argument("-c", "--cool-down", type=int, default = 10, help="the lowest tiem interval (in sec) between two images") | |
args = vars(ap.parse_args()) | |
#load camera | |
# initialize the camera and grab a reference to the raw camera capture | |
camera = PiCamera() | |
camera.vflip = True | |
camera.resolution = (640, 480) | |
camera.framerate = 32 | |
rawCapture = PiRGBArray(camera, size=(640, 480)) | |
#init the background substractor | |
fgbg = cv2.BackgroundSubtractorMOG2(history = 1000, varThreshold = 100, bShadowDetection = False) | |
lastDetection = time.time() | |
# loop over the frames of the video | |
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): | |
currentTime = time.time() | |
frame = frame.array | |
#resize, grayscale and blur | |
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
#gray = cv2.resize(gray, (640, 480)) | |
##gray = cv2.dilate(gray, None, iterations=2) | |
gray = cv2.GaussianBlur(gray, (11, 11), 0) | |
#bg substract method | |
bg = fgbg.apply(gray, learningRate = 1.0/150) | |
#addition stuff | |
bg = cv2.dilate(bg, None, iterations=2) | |
#bg = cv2.erode(bg, None, iterations=2) | |
(cnts, _) = cv2.findContours(bg.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
# loop over the contours | |
for c in cnts: | |
# if the contour is too small, ignore it | |
if cv2.contourArea(c) < args["min_area"]: | |
continue | |
# compute the bounding box for the contour, draw it on the frame, | |
# and update the text | |
(x, y, w, h) = cv2.boundingRect(c) | |
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) | |
# save this image, if not already saved | |
if lastDetection + args["cool_down"] < currentTime: | |
print "saving" | |
lastDetection = currentTime | |
nameString = "detected/" + time.ctime() + ".jpg" | |
cv2.imwrite(nameString, frame) | |
rawCapture.truncate(0) | |
cv2.waitKey(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment