Guest User

Detection moving object

a guest
Jan 30th, 2015
371
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.66 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # necessary imports
  5. import numpy as np  # for maths operations
  6. import cv2          # OpenCV for Python ver. 2.4.10
  7. import datetime     # for time stamp
  8.  
  9. # OpenCV can retieve any video source like
  10. # USB cam - cv2.VideoCapture(0) - where param is no. of USB device
  11. # Video - cv2.VideoCapture("video.avi") - where param is path to video
  12. # Video Stream - cv2.VideoCapture("http://192.168.0.101/stream.mpeg") - where param is path to stream
  13. cap = cv2.VideoCapture("video.avi")
  14.  
  15. # taking first frame as a background (background can be retaken later)
  16. # params are history, number of Gaussian mixtures and baground ratio
  17. # parameters were chosen experimentally
  18. bg = cv2.BackgroundSubtractorMOG(3, 100, 0.8)
  19.  
  20. # number of founded objects
  21. prev_contours = -1
  22.  
  23. # main loop of program
  24. while(1):
  25.     # read frame from source
  26.     # ret can be True or False, frame is readed image if ret is True
  27.     ret, frame = cap.read()
  28.  
  29.     # loop for operations if image was readed correctly
  30.     if ret == True:
  31.         # subtracting background from frame, it will return binary image with:
  32.         # white pixel it was diffrent on background and frame
  33.         # black if pixel was the same on both frames
  34.         fgmask = bg.apply(frame)
  35.        
  36.         # kernel is matrix full of ones, first param determinate size of it
  37.         kernel_open = np.ones((25,25),np.uint8)
  38.         kernel_close = np.ones((3,3),np.uint8)
  39.        
  40.         # morphology opening is erosion followed by dilatation
  41.         # removing noise in binary image
  42.         fgmask_open = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel_close)
  43.  
  44.         # morphology closing is dilatation followed by eresion (oposite for opening)
  45.         # usefull to close small holes inside foreground objects, or small black points in the object
  46.         fgmask_open_close = cv2.morphologyEx(fgmask_open, cv2.MORPH_CLOSE, kernel_open)
  47.        
  48.         # fiding the contours of objects in binary image
  49.         # params are source image, contour retrieval mode and contour approximation method
  50.         contours, hierarchy = cv2.findContours(fgmask_open_close,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  51.        
  52.         # drawing the contours if founded
  53.         if len(contours) > 0:
  54.             # loop for each founded contours
  55.             for i in range(len(contours)):
  56.                 cnt = contours[i]
  57.                 x,y,w,h = cv2.boundingRect(cnt)
  58.                 # drawing rectangle on founded object
  59.                 cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)
  60.  
  61.         # generate time stamp if there is new amount of moving objects in frames
  62.         if len(contours)!=prev_contours:
  63.             time_stamp = str(datetime.datetime.now().strftime("%H:%M:%S.%f"))[:-3]
  64.             print time_stamp + ' - contours: ' + str(len(contours))
  65.             prev_contours = len(contours)
  66.    
  67.         # show frame with image of each operation taken
  68.         cv2.imshow('masked',fgmask) # image with subtracted background
  69.         cv2.imshow('after_open',fgmask_open) # image after open
  70.         cv2.imshow('after_close',fgmask_open_close) # image after close
  71.         cv2.imshow('original',frame) # original image with contours on objects
  72.    
  73.         # keyboard key support
  74.         k = cv2.waitKey(30) & 0xff
  75.         # ESC to close
  76.         if k == 27:
  77.             break
  78.         #n to take new background image
  79.         if k == 110:
  80.             bg = cv2.BackgroundSubtractorMOG()
  81.     # close aplication if there is no readed image
  82.     else:
  83.         cap.release()
  84.         cv2.destroyAllWindows()
  85.         break
  86.  
  87. # close aplication after finishing main loop
  88. cap.release()
  89. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment