Python calls OpenCV to implement camera motion detection [Raspberry Pi]

Source: Internet
Author: User

[Hardware Environment]

Raspberrypi 3-Generation B (UK version)

[Software Environment]

Operating system: Raspbian

Python version: 2.7.3

Python Library:

1.1) Opencv-python (3.2.0.6)

[Construction process]

OpenCV Python Library:

1. PIP Installation

[The relevant code (temporarily unverified, removed from the author's original code in the Dropbox Automatic upload section)]

pi_surveillance.py

#USAGE#python pi_surveillance.py--conf Conf.json#Import the necessary packages fromPyimagesearch.tempimageImportTempimage fromPicamera.arrayImportPirgbarray#Picamera (CANT be imported on WINDOWS PLATFORM) fromPicameraImportPicamera#Picamera (CANT be imported on WINDOWS PLATFORM)ImportArgparseImportWarningsImportdatetimeImportimutilsImportJSONImport TimeImportCv2#construct the argument parser and the parse the argumentsAP =Argparse. Argumentparser () ap.add_argument ("- C","--conf", Required=true, help="path to the JSON configuration file") args=VARs (Ap.parse_args ())#filter warnings, load the configuration and initialize the DropboxClientWarnings.filterwarnings ("Ignore") Conf= Json.load (Open (args["conf"])) client=None#initialize the camera and grab a reference to the raw camera captureCamera =Picamera () camera.resolution= Tuple (conf["resolution"]) Camera.framerate= conf["fps"]rawcapture= Pirgbarray (Camera, Size=tuple (conf["resolution"]))#Allow the camera to warmup, then initialize the average frame, last#uploaded timestamp, and frame motion counterPrint "[INFO] warming up ..."Time.sleep (conf["Camera_warmup_time"]) Avg=nonelastuploaded=Datetime.datetime.now () motioncounter=0#capture Frames from the camera forFinchCamera.capture_continuous (Rawcapture, format="BGR", use_video_port=True):#grab the raw NumPy array representing the image and initialize    #The timestamp and occupied/unoccupied textframe =F.array Timestamp=datetime.datetime.now () text="unoccupied"    #Resize the frame, convert it to grayscale, and blur itframe = Imutils.resize (frame, width=500) Gray=Cv2.cvtcolor (frame, cv2. Color_bgr2gray) Gray= Cv2. Gaussianblur (Gray, (21, 21), 0)#If the average frame is None, initialize it    ifAvg isNone:Print "[INFO] Starting background model ..."avg= Gray.copy (). Astype ("float") rawcapture.truncate (0)Continue    #accumulate the weighted average between the current frame and    #previous frames, then compute the difference between the current    #frame and running averageCv2.accumulateweighted (Gray, AVG, 0.5) Framedelta=Cv2.absdiff (Gray, Cv2.convertscaleabs (avg))#threshold The delta image, dilate the thresholded image to fill    #in holes, then find contours on thresholded imageThresh = Cv2.threshold (Framedelta, conf["Delta_thresh"], 255, Cv2. thresh_binary) [1] Thresh= Cv2.dilate (Thresh, None, iterations=2) (CNTs, _)=cv2.findcontours (Thresh.copy (), Cv2. Retr_external, Cv2. Chain_approx_simple)#Loop over the contours     forCinchCNTs:#if the contour is too small, ignore it        ifCv2.contourarea (c) < conf["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) Text="occupied"    #Draw the text and timestamp on the frameTS = Timestamp.strftime ("%A%d%B%Y%i:%m:%s%p") Cv2.puttext (frame,"The Status: {}". Format (text), (10, 20), Cv2. Font_hershey_simplex,0.5, (0, 0, 255), 2) Cv2.puttext (frame, TS, (Ten, Frame.shape[0]-10), Cv2. Font_hershey_simplex,0.35, (0, 0, 255), 1)    #check to see if the occupied    ifText = ="occupied":        #Check to see if enough time have passed between uploads        if(timestamp-lastuploaded). Seconds >= conf["Min_upload_seconds"]:            #Increment the motion counterMotioncounter + = 1#Check to see if the number of frames with consistent motion is            #High enough            ifMotioncounter >= conf["Min_motion_frames"]:                #Check to see if Dropbox sohuld is used                ifconf["Use_dropbox"]:                    #write the image to temporary filet =tempimage () cv2.imwrite (T.path, frame)#upload the image to Dropbox and cleanup the tempory image                    Print "[UPLOAD] {}". Format (TS) path="{base_path}/{timestamp}.jpg". Format (Base_path=conf["Dropbox_base_path"], timestamp=ts) client.put_file (path, open (T.path,"RB") ) T.cleanup ()#update the last uploaded timestamp and reset the motion                #counterlastuploaded =timestamp Motioncounter=0#Otherwise, the hostel is not occupied    Else: Motioncounter=0#Check to see if the frames should is displayed to screen    ifconf["Show_video"]:        #Display the security feedCv2.imshow ("Security Feed", frame) key= Cv2.waitkey (1) & 0xFF#if the ' Q ' key is pressed, break from the Lop        ifKey = = Ord ("Q"):             Break    #clear the stream in preparation for the next frameRawcapture.truncate (0)
Conf.json
{    "Show_video": True,    "Use_dropbox": True,    "Dropbox_key": "Your_dropbox_key",    "Dropbox_secret": " Your_dropbox_secret ",    " Dropbox_base_path ":" Your_dropbox_app_path ",    " Min_upload_seconds ": 3.0,    " min _motion_frames ": 8,    " Camera_warmup_time ": 2.5,    " Delta_thresh ": 5,    " Resolution ": [640, 480],    " FPS ": +,    " Min_area ": 5000}
tempimage.py
#Import the necessary packagesImportUUIDImportOSclassTempimage:def __init__(Self, basepath="./", ext=". jpg"):        #construct the file pathSelf.path ="{Base_path}/{rand}{ext}". Format (base_path=BasePath, Rand=str (Uuid.uuid4 ()), ext=ext)defCleanup (self):#Remove the fileOs.remove (Self.path)

Python calls OpenCV to implement camera motion detection [Raspberry Pi]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.