Python calls OpenCV to implement camera motion detection

Source: Internet
Author: User

[Hardware Environment]

WIN10 64-bit

[Software Environment]

Python version: 2.7.3

Ide:jetbrains Pycharm 2016.3.2

Python Library:

1.1) Opencv-python (3.2.0.6)

[Construction process]

OpenCV Python Library:

1. Select the Opencv-python (3.2.0.6) library installation in the Pycharm plug-in source

[Related code]

#Encoding=utf-8#Import the necessary packagesImportArgparseImportdatetimeImportimutilsImport TimeImportCv2#Creating a parameter parser and resolving parametersAP =Argparse. Argumentparser () ap.add_argument ("- v","--video", help="path to the video file") ap.add_argument (" -A","--min-area", Type=int, default=500, help="Minimum area size") args=VARs (Ap.parse_args ())#If the video parameter is none, then we read the data from the cameraifArgs.get ("Video", None) isNone:camera=Cv2. Videocapture (0) Time.sleep (0.25)#Otherwise we read a video fileElse: Camera= Cv2. Videocapture (args["Video"])#Initialize the first frame of the video streamFirstframe =None#traverse each frame of the video whileTrue:#gets the current frame and initializes the occupied/unoccupied text(grabbed, frame) =camera.read () text="unoccupied"    #If we can't grab a frame, we're at the end of the video .    if  notgrabbed: Break    #Resize the frame, convert to grayscale, and Gaussian Blurframe = Imutils.resize (frame, width=500) Gray=Cv2.cvtcolor (frame, cv2. Color_bgr2gray) Gray= Cv2. Gaussianblur (Gray, (21, 21), 0)#If the first frame is none, initialize it    ifFirstframe isNone:firstframe=GrayContinue    #calculates the difference between the current frame and the first frameFramedelta =Cv2.absdiff (Firstframe, gray) Thresh= Cv2.threshold (Framedelta, 255, Cv2. thresh_binary) [1]    #Expand the threshold image to fill the hole, and then find the outline on the threshold imageThresh = Cv2.dilate (Thresh, None, iterations=2) Thresh, contours, hierarchy= Cv2.findcontours (Thresh.copy (), Cv2. Retr_external, Cv2. Chain_approx_simple)#The cv2.findcontours () function returns three values, the first one returns the image you are working with, the second is the contour itself, and the third is the corresponding property of each contour .    #traversing outlines     forCinchcontours:#if the contour is too small, ignore it        PrintCv2.contourarea (c)ifCv2.contourarea (c) < args["Min_area"]:            Continue        #compute the bounding box for the contour, draw it on the frame,        #and update the text        #calculates the bounding box of the outline, drawing the box in the current frame(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 frame    #write text and timestamp on the current frameCv2.puttext (Frame,"The Status: {}". Format (text), (10, 20), Cv2. Font_hershey_simplex,0.5, (0, 0, 255), 2) Cv2.puttext (frame, Datetime.datetime.now (). Strftime ("%A%d%B%Y%i:%m:%s%p"),        (Frame.shape[0], Cv2. Font_hershey_simplex, 0.35, (0, 0, 255), 1)    #Displays the current frame and logs whether the user presses the keyCv2.imshow ("Security Feed", frame) cv2.imshow ("Thresh", Thresh) cv2.imshow ("Frame Delta", Framedelta) key= Cv2.waitkey (1)    #If the Q key is pressed, jump out of the loop    ifKey = = Ord ("Q"):         Break#Clean up the camera resource and close the open windowcamera.release () cv2.destroyallwindows ( )

Python calls OpenCV to implement camera motion detection

Related Article

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.