Ask Your Question

Marciano Ng's profile - activity

2017-05-05 00:32:48 -0600 received badge  Enthusiast
2017-05-02 22:25:00 -0600 asked a question How can i set a automatic video recorder

I have a video stream i want it to start recording when it detects an object and stop when there is no one around and save it while its recording it is also taking photo of the stream. Than send it all to dropbox so far i have been able to to all except the "start recording when it detects an object and stop when there is no one around".
Is there anything i can do to make it work?

Im working with python, linux OS , webcam
The below is my code :

import sys
sys.path.append('/usr/local/lib/python3.4/site-packages')
import numpy as np
import cv2
import imutils
from imutils import contours
import datetime
import time
import dropbox


dbx = dropbox.Dropbox('-------------------------------------------------')
dbx.users_get_current_account()


#cap = cv2.VideoCapture("/home/pi/Desktop/Proj/VideoTestSample.mp4")
cap = cv2.VideoCapture(1)

fgbg = cv2.createBackgroundSubtractorMOG2()

#Set format
fourcc = cv2.VideoWriter_fourcc(*'XVID')
#Get Datetime
timestr = time.strftime("%Y_%m_%d_%H_%M_%S")
#Creating name of folder
timestr = timestr + '.avi'
#Setting Name, Format, FPS, FrameSize
out = cv2.VideoWriter(timestr,fourcc, 20.0, (640,480))

#As long as the VideoCapture is open loop to show the frames
while (cap.isOpened()):
    #capture frame-by-frame
    (grabbed, frame) = cap.read()
    text = " "

    if not grabbed:
        break

    #Blur the image as in remove noise 
    frame = cv2.medianBlur(frame, 5)
    #Convert frame to Black white and gray
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)


    #Apply the Background SubtractionMOG2
    fgmask = fgbg.apply(gray)
    #Erode away the boundaries of the foreground object
    thresh = cv2.erode(fgmask, None, iterations=2)

    #Set detect as none
    detect = None

    #Find outline of a new foreground object from thresh after the erossion
    (_,cnts,hierarchy) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    #detect is object found or not found
    detect = (_,cnts,hierarchy)

    #if object found is detected run these codes
    if detect == (_,cnts,hierarchy):

        #if area of object is lower than 300 ignore it 
        for (i,c) in enumerate(cnts):
            if cv2.contourArea(c) < 300:
                continue

            #Draw Rectangle around found contour object
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
            #Draw number of object above the rectangle
            cv2.putText(frame, "#{}".format(i + 1), (x, y - 15),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
            text = "REC"


            #Capture image
            print("Capturing frame")
            timestring = time.strftime("%Y_%m_%d_%H_%M_%S")
            image_timestr = 'image_' + timestring + '.png'
            cv2.imwrite(image_timestr, frame)

            #Opening for [r]eading as [b]inary
            ImageFile = open(image_timestr, mode = "rb")
            #Reads the number of bytes of the video
            data = ImageFile.read()

            #Setting the save location with file name
            SavetoLocation = '/FYP_Image_Save/'+ image_timestr
            SaveToLocation = str(SavetoLocation)

            detect= None 

            if detect != (_,cnts,hierarchy):
                print("Stop recording")

    elif  detect != (_,cnts,hierarchy):
        print("Not recording")

    else:
        continue

    #Draw the text at top right hand corner
    cv2.putText(frame, "{}". format(text), (10,20),
                cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
    #Draw the DateTime on the bottom left hand corner
    cv2.putText(frame, datetime.datetime.now().strftime("%A %d ...
(more)
2017-04-25 04:32:52 -0600 commented question How do i add Meanshift together with BackgroundSubtractorMOG2

@berak Sorry i didnt know it was posted so i made another

2017-04-25 00:27:18 -0600 asked a question How do i add Meanshift together with BackgroundSubtractorMOG2

My current code below is that it creates a new rectangle on every frame what i wish to do is add the meanshift to my current code so that it would follow the object matching with the previous frame.

The tutorials doesnt really help as i find it confusing and doesn't explain the properly what each part of the code does and how it works.

Please help me i need this done for my final project

import sys
sys.path.append('/usr/local/lib/python3.4/site-packages')
import numpy as np
import cv2
import imutils
from imutils import contours
import datetime
import time

#cap = cv2.VideoCapture("/home/pi/Desktop/Proj/VideoTestSample.mp4")
cap = cv2.VideoCapture(0)

fgbg = cv2.createBackgroundSubtractorMOG2()

while (cap.isOpened()):
    (grabbed, frame) = cap.read()
    text = " "

    if not grabbed:
        break

    frame = imutils.resize(frame, width=500)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray, 5)

    fgmask = fgbg.apply(gray)
    thresh = cv2.erode(fgmask, None, iterations=2)
    (_,cnts,hierarchy) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for (i,c) in enumerate(cnts):
        if cv2.contourArea(c) < 300:
            continue

        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
        cv2.putText(frame, "#{}".format(i + 1), (x, y - 15),
            cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)        
        text = "REC"

    cv2.putText(frame, "Room 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"),
                (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35,(0,0,255), 1)

    cv2.imshow('frame',frame)
    cv2.imshow('gray', gray)
    cv2.imshow('fgmask', fgmask)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
2017-04-25 00:26:46 -0600 asked a question BackgroundSubtractionMOG2 + Mean-Shift Tracking

I have searched multiple tutorials on how to track objects coming in and out of the frame but so far i have only been able to

  1. BackgroundSubtractionMOG2
  2. Draw rectangles on the white parts

However i cant seem to make the program to track the the object instead of drawing a new rectangle every new frame in need it to recognize it from the previous frame so i have decided to use Mean-Shift but i cant seem to understand how to use it with MOG2.

Please help me

I am currently using Python 3.4.0, OpenCV 3.1 and Numpy
This is my current code is below:

import sys
sys.path.append('/usr/local/lib/python3.4/site-packages')
import numpy as np
import cv2
import imutils
from imutils import contours
import datetime
import time

cap = cv2.VideoCapture("/home/pi/Desktop/Proj/VideoTestSample.mp4")
cap = cv2.VideoCapture(0)

fgbg = cv2.createBackgroundSubtractorMOG2()

while (cap.isOpened()):
    (grabbed, frame) = cap.read()
    text = " "

    if not grabbed:
        break

    frame = imutils.resize(frame, width=500)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.medianBlur(gray, 5)

    fgmask = fgbg.apply(gray)
    thresh = cv2.erode(fgmask, None, iterations=2)
    (_,cnts,hierarchy) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    for (i,c) in enumerate(cnts):
        if cv2.contourArea(c) < 300:
            continue

        (x, y, w, h) = cv2.boundingRect(c)
        cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 2)
        cv2.putText(frame, "#{}".format(i + 1), (x, y - 15),
            cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)        
        text = "REC"

    cv2.putText(frame, "{}". 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"),
                (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35,(0,0,255), 1)

    cv2.imshow('frame',frame)
    cv2.imshow('gray', gray)
    cv2.imshow('fgmask', fgmask)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()