User avatar
DougieLawson
Posts: 37129
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Lightweight python motion detection

Mon Mar 17, 2014 12:40 pm

geneworld wrote:Still looking for help with my picasa issue :?
I'd recommend starting a new thread and restating your problem.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

MrJusts
Posts: 1
Joined: Thu Mar 20, 2014 7:46 pm

Re: Lightweight python motion detection

Sat Mar 22, 2014 5:50 pm

Hello guys

How to stream live video stream over http in the same time running this motion detection script ?

Motion detection script work's great !

About Live streaming over http I used mjpg-streamer, but when it starts, the motion detection don't work anymore.

activematrix
Posts: 2
Joined: Sat Mar 22, 2014 9:13 pm

Re: Lightweight python motion detection

Sat Mar 22, 2014 9:22 pm

Thanks for the awesome script!

I am having a problem, though and I was wondering if anyone has any insight. I am using the variant of Brainflakes' script improved by pageauc, peewee2 and Kesthal, and I am having a recurring issue with corruption and erroneous motion detection. The output looks like this: Image

The color and area of the file messed up varies, and I am guessing that this is what is also causing the erroneous capture.

I have tried increasing the timeout by increasing the -t parameter to 500, then 700, then 1000 in both calls to raspistill to no avail.

I have not had this issue with this camera in the past. I am using a Pi Noir camera.

Thanks a million!
- Chris

User avatar
DougieLawson
Posts: 37129
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Lightweight python motion detection

Sat Mar 22, 2014 9:33 pm

Check the ribbon cable (both ends).
Check the "sunny" connector on the camera board.

NOTE: earth yourself first the camera is very sensitive to ESD.
Note: Having anything humorous in your signature is completely banned on this forum. Wear a tin-foil hat and you'll get a ban.

Any DMs sent on Twitter will be answered next month.

This is a doctor free zone.

activematrix
Posts: 2
Joined: Sat Mar 22, 2014 9:13 pm

Re: Lightweight python motion detection

Fri Mar 28, 2014 3:35 pm

I checked all of the ribbons, and they are fine. A simple call to raspistill produces a perfect photo 99% of the time, but this script produces messed up photos probably 75% of the time.

akhilchirravuri
Posts: 18
Joined: Thu Jan 02, 2014 4:23 pm

Re: Lightweight python motion detection

Mon Mar 31, 2014 1:41 pm

hey...after making certain modifications the code worked...nice job...but the file won't save to the specified location I.,e (home/pi/nasbox/picam)...

I want to save the file for my project...help me...

akhilchirravuri
Posts: 18
Joined: Thu Jan 02, 2014 4:23 pm

Re: Lightweight python motion detection

Mon Mar 31, 2014 1:44 pm

hey...after making certain modifications the code worked...nice job...but the file won't save to the specified location I.,e (home/pi/nasbox/picam)...

I want to save the file for my project...is there anyother way to save the file...? help me... :)

HerrJemineh
Posts: 10
Joined: Tue Aug 13, 2013 1:35 pm

Re: Lightweight python motion detection

Thu Apr 17, 2014 10:25 am

Hello,
does anyone know why my pictures always have different color values​​?
If I manually receiving a picture via raspistill, everything is in ok ...
I use the following script which uploads the taken pictures to my dropbox:

Code: Select all

#!/usr/bin/python

    # original script by brainflakes, improved by pageauc, peewee2 and Kesthal
    # www.raspberrypi.org/phpBB3/viewtopic.php?f=43&t=45235

    # You need to install PIL to run this script
    # type "sudo apt-get install python-imaging-tk" in an terminal window to do this

    # play with it KLL
    # /home/pi/python_cam/picam4.py
    # rev b with dropbox, ftp, email options
    
import StringIO
import subprocess
import os
import time
from datetime import datetime
from PIL import Image

# Import smtplib to provide email functions
import smtplib
#from email.mime.text import MIMEText

    # Motion detection settings:
    # Threshold          - how much a pixel has to change by to be marked as "changed"
    # Sensitivity        - how many changed pixels before capturing an image, needs to be higher if noisy view
    # ForceCapture       - whether to force an image to be captured every forceCaptureTime seconds, values True or False
    # filepath           - location of folder to save photos
    # filenamePrefix     - string that prefixes the file name for easier identification of files.
    # diskSpaceToReserve - Delete oldest images to avoid filling disk. How much byte to keep free on disk.
    # cameraSettings     - "" = no extra settings; "-hf" = Set horizontal flip of image; "-vf" = Set vertical flip; "-hf -vf" = both horizontal and vertical flip
threshold   = 10
sensitivity = 140
rotation    = 180               # KLL camera mounting

forceCapture = True
forceCaptureTime = 1 * 60 # every minute for webserver* 60      # Once an hour

        # info by print
info_print = True

        # store image files to temp fs 
filepath       = "/run/shm/"
filenamePrefix = "RPICAM"
file_typ       = ".jpg"

prg_msg = "boot"  # used to get more info in print when a picture is made

        # option and the newest one is referred to by a linkfile in same dir
link_tolastpicture = True       # KLL 
lfile = "last.jpg"              # KLL make it as symlink

        # option send file to DROPBOX, ! very long API procedure !
send_dropbox = False            # KLL test files in drop_box and to PC

        # option send ( or move ) file to a FTP server 
send_ftp     = False             # KLL FTP
ftp_remotepath = "/usb1_1/rpi/"                         # a USB stick
ftp_account = "kll-ftp:*****@192.168.1.1:2121"          # in my router: USER:[email protected]:PORT

#wput_option = " -R"            # opt "-R" for move file
wput_option = " "

        # option email
send_email_enable = False
# Define email addresses to use
addr_to   = '[email protected]'
addr_from = '[email protected]'

# Define SMTP email server details
GMAIL_USER = '[email protected]'
GMAIL_PASS = '*****'
SMTP_SERVER = 'smtp.gmail.com:587'

# email control
emaildeltaTime = 1 * 60 * 60                    # send mail again only after ... hour
last_send = time.time() - emaildeltaTime        # so first picture ( at start / boot ) also makes a email

# temp fs ?100MB? should keep 10MB for other program to use
diskSpaceToReserve = 10 * 1024 * 1024   # Keep 10 mb free on disk
# with 95*1024*1024 == 99614720 it deletes all ??
# delets always a file each time is makes a new one! 
# with 90*1024*1024 == 94371840 it deletes (one) the oldest.


cameraSettings = ""

    # settings of the photos to save
saveWidth   = 1296
saveHeight  = 972
saveQuality = 15 # Set jpeg quality (0 to 100)

    # Test-Image settings
testWidth = 100
testHeight = 75

    # this is the default setting, if the whole image should be scanned for changed pixel
testAreaCount = 1
testBorders = [ [[1,testWidth],[1,testHeight]] ]  # [ [[start pixel on left side,end pixel on right side],[start pixel on top side,stop pixel on bottom side]] ]
    # testBorders are NOT zero-based, the first pixel is 1 and the last pixel is testWith or testHeight

    # with "testBorders", you can define areas, where the script should scan for changed pixel
    # for example, if your picture looks like this:
    #
    #     ....XXXX
    #     ........
    #     ........
    #
    # "." is a street or a house, "X" are trees which move arround like crazy when the wind is blowing
    # because of the wind in the trees, there will be taken photos all the time. to prevent this, your setting might look like this:

    # testAreaCount = 2
    # testBorders = [ [[1,50],[1,75]], [[51,100],[26,75]] ] # area y=1 to 25 not scanned in x=51 to 100

    # even more complex example
    # testAreaCount = 4
    # testBorders = [ [[1,39],[1,75]], [[40,67],[43,75]], [[68,85],[48,75]], [[86,100],[41,75]] ]

    # in debug mode, a file debug.bmp is written to disk with marked (?GREEN?) changed pixel an with marked border of scan-area
    # debug mode should only be turned on while testing the parameters above
debugMode = False # False or True
debug_bmp = "debug.bmp"


def send_email(recipient, subject, text):
        smtpserver = smtplib.SMTP(SMTP_SERVER)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(GMAIL_USER, GMAIL_PASS)
        header = 'To:' + recipient + '\n' + 'From: ' + GMAIL_USER
        header = header + '\n' + 'Subject:' + subject + '\n'
        msg = header + '\n' + text + ' \n\n'
        smtpserver.sendmail(GMAIL_USER, recipient, msg)
        smtpserver.close()

    # Capture a small test image (for motion detection)
def captureTestImage(settings, width, height):
        command = "raspistill %s -w %s -h %s -t 200 -e bmp -n -o -" % (settings, width, height)
        imageData = StringIO.StringIO()
        imageData.write(subprocess.check_output(command, shell=True))
        imageData.seek(0)
        im = Image.open(imageData)
        buffer = im.load()
        imageData.close()
        return im, buffer

    # Save a full size image to disk
def saveImage(settings, width, height, quality, diskSpaceToReserve):
        global last_send #it is read and set here
        keepDiskSpaceFree(diskSpaceToReserve)
        #time = datetime.now()    # KLL bad to call this variable time !
        t_now = datetime.now()
        s_now = "-%04d%02d%02d-%02d%02d%02d" % (t_now.year, t_now.month, t_now.day, t_now.hour, t_now.minute, t_now.second)
        filename = filenamePrefix + s_now + file_typ
        fullfilename = filepath + filename
        lastfilename = filepath + lfile
        subprocess.call("raspistill %s -w %s -h %s -t 200 -e jpg -q %s -n -rot %s -o %s" % (settings, width, height, quality, rotation, fullfilename), shell=True)
        if info_print :
                print " %s captured %s" % (prg_msg,fullfilename)

        if link_tolastpicture : # tested ok
                try:
                        os.remove(lastfilename)
                except:
                        pass # not exist at first start
                os.symlink(fullfilename,lastfilename)
#               os.chmod(lastfilename,stat.S_IXOTH)    #stat.S_IRWXG
                pass

        if send_dropbox : # tested ok
                subprocess.call("/home/pi/python_cam/dropbox_uploader.sh upload %s /RPICAM1/" % (fullfilename), shell=True)
                if info_print :
                        print "upload dropbox"
                pass

        if send_ftp :  # only works from that dir! # tested ok
                if info_print :
                        wput_opt = wput_option
                        pass
                else :
                        wput_opt = wput_option+" -q" # quiet
                        pass
                os.chdir(filepath)
                subprocess.call("wput %s %s ftp://%s%s" % (wput_opt,filename,ftp_account,ftp_remotepath), shell=True)
                os.chdir("/")
                if info_print :
                        print "upload ftp"
                pass

        if send_email_enable :
                #print 'now: %s' % (str( time.time()))
                #print 'last_send: %s' % (str(last_send))
                #print 'emaildeltaTime: %s' % (str( emaildeltaTime ))
                if time.time() - last_send > emaildeltaTime :
                        emailsubject = 'from RPI CAM1: '
                        emailtext    = 'motion detect: ' + fullfilename
                        send_email(addr_to, emailsubject , emailtext)
                        last_send = time.time()
                        if info_print :
                                print "send email"
                        pass
                pass

    # Keep free space above given level
def keepDiskSpaceFree(bytesToReserve):
        if (getFreeSpace() < bytesToReserve):
            os.chdir(filepath)     #KLL now works better
            for dfilename in sorted(os.listdir(filepath)):
                if dfilename.startswith(filenamePrefix) and dfilename.endswith(file_typ):
                    print "Deleted %s to avoid filling disk" % (dfilename)
                    os.remove(dfilename)
                    if (getFreeSpace() > bytesToReserve):
                        os.chdir("/")  # KLL
                        return

    # Get available disk space
def getFreeSpace():
        st = os.statvfs(filepath)
        du = st.f_bavail * st.f_frsize
        #print " free space: %s " % (du)
        return du

#_________ main ________________________________________________________________________________________
    # Get first image
if info_print :
        print('get first image')
image1, buffer1 = captureTestImage(cameraSettings, testWidth, testHeight)

    # Reset last capture time
lastCapture = time.time()

if info_print :
        print('start loop')   # and take a very first picture to see start time ...
        

saveImage(cameraSettings, saveWidth, saveHeight, saveQuality, diskSpaceToReserve)
prg_msg = "motion"

while (True):

        # Get comparison image
        image2, buffer2 = captureTestImage(cameraSettings, testWidth, testHeight)

        # Count changed pixels
        changedPixels = 0
        takePicture = False

        if (debugMode): # in debug mode, save a bitmap-file with marked changed pixels and with visible testarea-borders
            debugimage = Image.new("RGB",(testWidth, testHeight))
            debugim = debugimage.load()

        for z in xrange(0, testAreaCount): # = xrange(0,1) with default-values = z will only have the value of 0 = only one scan-area = whole picture
            for x in xrange(testBorders[z][0][0]-1, testBorders[z][0][1]): # = xrange(0,100) with default-values
                for y in xrange(testBorders[z][1][0]-1, testBorders[z][1][1]):   # = xrange(0,75) with default-values; testBorders are NOT zero-based, buffer1[x,y] are zero-based (0,0 is top left of image, testWidth-1,testHeight-1 is botton right)
                    if (debugMode):
                        debugim[x,y] = buffer2[x,y]
                        if ((x == testBorders[z][0][0]-1) or (x == testBorders[z][0][1]-1) or (y == testBorders[z][1][0]-1) or (y == testBorders[z][1][1]-1)):
                            # print "Border %s %s" % (x,y)
                            debugim[x,y] = (0, 0, 255) # in debug mode, mark all border pixel to blue
                    # Just check green channel as it's the highest quality channel
                    pixdiff = abs(buffer1[x,y][1] - buffer2[x,y][1])
                    if pixdiff > threshold:
                        changedPixels += 1
                        if (debugMode):
                            debugim[x,y] = (0, 255, 0) # in debug mode, mark all changed pixel to green
                    # Save an image if pixels changed
                    if (changedPixels > sensitivity):
                        takePicture = True # will shoot the photo later
                    if ((debugMode == False) and (changedPixels > sensitivity)):
                        break  # break the y loop
                if ((debugMode == False) and (changedPixels > sensitivity)):
                    break  # break the x loop
            if ((debugMode == False) and (changedPixels > sensitivity)):
                break  # break the z loop

        if (debugMode):
            debugimage.save(filepath + debug_bmp) # save debug image as bmp
            print "debug.bmp saved, %s changed pixel" % changedPixels
        # else:
        #     print "%s changed pixel" % changedPixels

        # Check force capture
        if forceCapture:
                #print 'now: %s' % (str( time.time()))
                #print 'lastCapture: %s' % (str(lastCapture))
                #print 'forceCaptureTime: %s' % (str( forceCaptureTime ))
                if time.time() - lastCapture > forceCaptureTime:
                        takePicture = True
                        prg_msg = "force"

        if takePicture:
            lastCapture = time.time()
            saveImage(cameraSettings, saveWidth, saveHeight, saveQuality, diskSpaceToReserve)
            prg_msg = "motion"

        # Swap comparison buffers
        image1 = image2
        buffer1 = buffer2

and get colours like you can see in the attachment.

Regards
HerrJemineh
Attachments
1.jpg
1.jpg (42.3 KiB) Viewed 7298 times

telgo
Posts: 1
Joined: Thu Apr 17, 2014 6:36 pm

Re: Lightweight python motion detection

Thu Apr 17, 2014 8:31 pm

When I try this script, nothing happens. After some hours (i took a nap!), I interrupted
the process with CTRL-C, and the Traceback seems to indicate that the write to subprocess
never completes.

File "motiondetect.py", line 70, in <module>
image1, buffer1 = captureTestImage()
File "motiondetect.py", line 38, in captureTestImage
imageData.write(subprocess.check_output(command, shell=True))
File "/usr/lib/python2.7/subprocess.py", line 538, in check_output
output, unused_err = process.communicate()
File "/usr/lib/python2.7/subprocess.py", line 746, in communicate
stdout = _eintr_retry_call(self.stdout.read)
File "/usr/lib/python2.7/subprocess.py", line 478, in _eintr_retry_call
return func(*args)
KeyboardInterrupt

Any clues?

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sat Apr 19, 2014 9:23 pm

telgo, when the script hangs, you have propably set the t-value to 0 in the raspistill-command.

The command must look like this:

Code: Select all

command = "raspistill %s -w %s -h %s -t 200 -e bmp -n -o -" % (settings, width, height)
The t-value must be greater than 0!
jamesh wrote:-t 0 is the setting for run forever.
The t value is in milliseconds, and you need about 750 minimum for the camera to start up and get a decent picture. (it needs time for the exposure calculation to stabilise)

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sat Apr 19, 2014 10:02 pm

HerrJemineh wrote:Hello,
does anyone know why my pictures always have different color values​​?
If I manually receiving a picture via raspistill, everything is in ok ...
Every time, when the raspistill-command is executed, the camera tries to choose the correct exposure mode, white balance, brightness, sharpness, contrast, saturation, ...

Sometimes, the camera decides to take the picture more bright. I sometimes have these problems in the morning and the evening, when the light is very weak. You can try to set the values ​​manually, but then the pictures are probably too bright in strong light and dark in low light.

See page 6 and 7 of http://www.raspberrypi.org/wp-content/u ... tation.pdf to see how to change the values ​​manually.

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sat Apr 19, 2014 10:13 pm

akhilchirravuri wrote:hey...after making certain modifications the code worked...nice job...but the file won't save to the specified location I.,e (home/pi/nasbox/picam)...

I want to save the file for my project...is there anyother way to save the file...? help me... :)
You must change these settings:

Code: Select all

filepath = "/home/pi/picam"
filenamePrefix = "capture"
These values are used when you save the image:

Code: Select all

def saveImage(settings, width, height, quality, diskSpaceToReserve):
    keepDiskSpaceFree(diskSpaceToReserve)
    time = datetime.now()
    filename = filepath + "/" + filenamePrefix + "-%04d%02d%02d-%02d%02d%02d.jpg" % (time.year, time.month, time.day, time.hour, time.minute, time.second)
    subprocess.call("raspistill %s -w %s -h %s -t 200 -e jpg -q %s -n -o %s" % (settings, width, height, quality, filename), shell=True)
    print "Captured %s" % filename

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sat Apr 19, 2014 11:09 pm

MrJusts wrote:How to stream live video stream over http in the same time running this motion detection script ?
The camera can't be used with 2 different programs at the same time.

You can use the linux command tee to split the output, but the pi will probably break down when you try to use too many programs at the same time.
If you have a big linux-server, you can stream the output and make the jobs there:
on the server:
mkfifo video-stream
nc -l 5001 | tee video-stream | mplayer -cache 1024 -vo jpeg -nosound -fps 6 - (split stream in pics to save or as input for program motion)
cat video-stream | cvlc stream:///dev/stdin --sout '#standard{access=http,mux=ts,dst=:8554}' :demux=h264 (make http-stream)

on your pi:
raspivid -t 0 --nopreview -o - | nc 192.168.178.42 5001

But this is off-topic!!

234234234
Posts: 4
Joined: Sat Apr 19, 2014 11:15 pm

I am having trouble with the below code :(

Sat Apr 19, 2014 11:22 pm

Thanks for the code all who contributed. I would like to set it up to delete the oldest capture but I can't for the life of me figure it out, any help would be greatly appreciated on what parameters to input into the # Keep free space above given level line in order to accomplish this.

Code: Select all

#!/usr/bin/python2.7
# detect motion and save video file (.avi)
import StringIO
import subprocess
import os
import time
from datetime import datetime
from PIL import Image

# Original code written by brainflakes and modified to exit
# image scanning for loop as soon as the sensitivity value is exceeded.
# this can speed taking of larger photo if motion detected early in scan
 
# Motion detection settings:
# PGM maded changes to read values dynamically via command line parameters.
# --------------------------
# Threshold      - (how much a pixel has to change by to be marked as "changed")
# Sensitivity    - (how many changed pixels before capturing an image) needs to be higher if noisy view
# ForceCapture   - (whether to force an image to be captured every forceCaptureTime seconds)
# filepath       - location of folder to save photos
# filenamePrefix - string that prefixes the file name for easier identification of files.

threshold = 10
sensitivity = 180
forceCapture = True
forceCaptureTime = 60 * 60 # Once an hour
CaptureDuration = 25000  #mS
filepath = "/home/pi/video"
filenamePrefix = "pgm"
fileType = "avi"
# File photo size settings
saveWidth = 1280
saveHeight = 800
diskSpaceToReserve = 40 * 1024 * 1024 # Keep 40 mb free on disk

# Capture a small test image (for motion detection)
def captureTestImage():
    command = "raspistill -w %s -h %s -t 1 -n -e bmp -o -" % (100, 75)
    imageData = StringIO.StringIO()
    imageData.write(subprocess.check_output(command, shell=True))
    imageData.seek(0)
    im = Image.open(imageData)
    buffer = im.load()
    imageData.close()
    return im, buffer

# Save a full size video image to disk
def saveImage(width, height, diskSpaceToReserve):
    keepDiskSpaceFree(diskSpaceToReserve)
    time = datetime.now()
    filename = "/home/pi/video/" + filenamePrefix + "-%04d_%02d_%02d-%02d:%02d:%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second)+ "." + fileType
    subprocess.call("raspivid -w "+ str(saveWidth) +" -h "+ str(saveHeight) + " -t " + str(CaptureDuration) + " -n -o %s" % filename, shell=True)
    print "Captured %s" % filename

# Keep free space above given level
def keepDiskSpaceFree(bytesToReserve):
    if (getFreeSpace() < bytesToReserve):
        for filename in sorted(os.listdir(".")):
            if filename.startswith(filenamePrefix) and filename.endswith("." + fileType):
                os.remove(filename)
                print "Deleted %s to avoid filling disk" % filename
                if (getFreeSpace() > bytesToReserve):
                    return

# Get available disk space
def getFreeSpace():
    st = os.statvfs(".")
    du = st.f_bavail * st.f_frsize
    return du

#---------------------------------------------------------        

# Get first image
image1, buffer1 = captureTestImage()

# Reset last capture time
lastCapture = time.time()

# added this to give visual feedback of camera motion capture activity.  Can be removed as required
os.system('clear')
print "            Motion Detection Started"
print "            ------------------------"
print "Pixel Threshold (How much)   = " + str(threshold)
print "Sensitivity (changed Pixels) = " + str(sensitivity)
print "Video Capture Duration: " + str(CaptureDuration/1000) + " secs"
print "Video Resolution: "+ str(saveWidth)+"x"+str(saveHeight) + "\n"
print "---------- Motion Capture File Activity --------------"

while (True):

    # Get comparison image
    image2, buffer2 = captureTestImage()

    # Count changed pixels
    changedPixels = 0
    for x in xrange(0, 100):
        # Scan one line of image then check sensitivity for movement
        for y in xrange(0, 75):
            # Just check green channel as it's the highest quality channel
            pixdiff = abs(buffer1[x,y][1] - buffer2[x,y][1])
            if pixdiff > threshold:
                changedPixels += 1

        # Changed logic - If movement sensitivity exceeded then
        # Save image and Exit before full image scan complete
        if changedPixels > sensitivity:   
            lastCapture = time.time()
            saveImage(saveWidth, saveHeight, diskSpaceToReserve)
            break
        continue

    # Check force capture
    if forceCapture:
        if time.time() - lastCapture > forceCaptureTime:
            changedPixels = sensitivity + 1
  
    # Swap comparison buffers
    image1  = image2
    buffer1 = buffer2
#------------------------------------------------------------

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sat Apr 19, 2014 11:37 pm

arshadhs wrote:I have noticed that after a day or two either the script stops working or I am not able to ssh into the pi and I have to restart it.
Sometimes, I have these problems, too :(

I reboot the pi every night with a cron-job to prevent these problems.

Maybe the camera is running out of GPU memory? Check config.txt in the /boot/ folder. The gpu_mem option should be at least 128.

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: I am having trouble with the below code :(

Sun Apr 20, 2014 7:42 am

234234234 wrote:Thanks for the code all who contributed. I would like to set it up to delete the oldest capture but I can't for the life of me figure it out, any help would be greatly appreciated on what parameters to input into the # Keep free space above given level line in order to accomplish this.
You must do nothing to delete the oldest capture, your code is already deleting the oldest capture :P

The command for filename in sorted(os.listdir(".")) in your keepDiskSpaceFree-function returns a sorted list of your captures, and as your captures have the name pgm-2014_04_18-14:19:20.avi, the oldest capture will be on top of the sorted list and will be deleted first. After deleting the oldest capture, the function checks again if the second oldest capture must be deleted, too. And so on. The function stops deleting, when the free disk space is greater than diskSpaceToReserve.

234234234
Posts: 4
Joined: Sat Apr 19, 2014 11:15 pm

Re: Lightweight python motion detection

Sun Apr 20, 2014 9:36 am

Image
Image

I set the diskSpaceToReserve to 9GB as a test but the oldest capture does not get deleted. :? any tips?

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sun Apr 20, 2014 9:57 am

Have you set your value to this?

Code: Select all

diskSpaceToReserve = 9 * 1024 * 1024 * 1024 # Keep 9 GB free on disk
It should work.

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sun Apr 20, 2014 10:10 am

The free space is slightly smaller than the value in diskSpaceToReserve, because you delete the old files before you capture the latest video. You can call the keepDiskSpaceFree-function again after you captured a new video.

Code: Select all

def saveImage(width, height, diskSpaceToReserve):
    keepDiskSpaceFree(diskSpaceToReserve)
    time = datetime.now()
    filename = "/home/pi/video/" + filenamePrefix + "-%04d_%02d_%02d-%02d:%02d:%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second)+ "." + fileType
    subprocess.call("raspivid -w "+ str(saveWidth) +" -h "+ str(saveHeight) + " -t " + str(CaptureDuration) + " -n -o %s" % filename, shell=True)
    keepDiskSpaceFree(diskSpaceToReserve) # new, delete old files again!!!!!!!!!
    print "Captured %s" % filename

234234234
Posts: 4
Joined: Sat Apr 19, 2014 11:15 pm

Re: Lightweight python motion detection

Sun Apr 20, 2014 4:54 pm

Tried what you said to no avail. It keeps on filling up the entire SD card until the pi is corrupt on reboot. Same happens when I use the original "diskSpaceToReserve = 40 * 1024 * 1024 # Keep 40 mb free on disk" -_-

Kesthal
Posts: 17
Joined: Sun Jul 21, 2013 8:47 pm

Re: Lightweight python motion detection

Sun Apr 20, 2014 7:27 pm

In function keepDiskSpaceFree, change the line
for filename in sorted(os.listdir(".")):
to this:
for filename in sorted(os.listdir(filepath + "/")):

In function keepDiskSpaceFree, change the lines
os.remove(filename)
print "Deleted %s to avoid filling disk" % filename
to this:
os.remove(filepath + "/" + filename)
print "Deleted %s/%s to avoid filling disk" % (filepath,filename)

In function saveImage, change the line
filename = "/home/pi/video/" + filenamePrefix + "-%04d_%02d_%02d-%02d:%02d:%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second)+ "." + fileType
subprocess.call("raspivid -w "+ str(saveWidth) +" -h "+ str(saveHeight) + " -t " + str(CaptureDuration) + " -n -o %s" % filename, shell=True)
to this:
filename = filepath + "/" + filenamePrefix + "-%04d_%02d_%02d-%02d:%02d:%02d" % (time.year, time.month, time.day, time.hour, time.minute, time.second)+ "." + fileType
subprocess.call("raspivid -w "+ str(width) +" -h "+ str(height) + " -t " + str(CaptureDuration) + " -n -o %s" % filename, shell=True)

In function getFreeSpace, change the line
st = os.statvfs(".")
to this:
st = os.statvfs(filepath + "/")

Your skript had all the errors that were corrected on page 1 and 2 of this threat. Your ForceCapture feature will also not work.
For everybody else:
If you want to get this skript running, follow this instruction
http://www.raspberrypi.org/forums/viewt ... 90#p394590 an take this skript: http://pastebin.com/yH7JHz9w

In this skript, all known errors are corrected and you have new features like excluding some areas from motion-detection.

234234234
Posts: 4
Joined: Sat Apr 19, 2014 11:15 pm

Re: Kesthal

Mon Apr 21, 2014 12:51 pm

Can you please direct me to the current working version of the python video motion capture script?

I am not having success implementing your corrections for the image script into to the video script (I am not knowledgeable on the subject).

Kind regards.

pageauc
Posts: 224
Joined: Fri Jan 04, 2013 10:52 pm

Lightweight python motion detection and grive syncing

Sat May 03, 2014 1:19 pm

Package using python motion capture with file syncing to google drive using pre compiled version of grive

Latest Update Information 3-May-2014
Here is a link to my latest Robin Cam video http://youtu.be/JnUaB1GVVTk using motion detection with grive sync to my google drive capability. The YouTube video comments Includes instructions for downloading readme.txt and tar files, Also see links below. The tar file includes a compiled version of grive plus a setup script to install required libraries to save everyone the effort of compiling the grive code for the RPI.. The Robin Cam setup does not currently use the grive option since it can connect to my home network via wifi. See below for details of my remote 3000 km away camera setup that has to use grive.

These files are on github.
Download setup instructions here https://raw.github.com/pageauc/pi-motio ... Readme.txt
Download tar file containing all the files here https://raw.github.com/pageauc/pi-motio ... motion.tar

My Remote Security Camera Setup using grive
I have this setup working at a remote location 3000 km away and it allows me to monitor things. As the camera is on a park private network I cannot SSH into my RPI security camera so you have to take special precautions. My setup has a UPS and runs a cron job to reboot the RPI every night. The synchronization script is setup to prevent grive from activating unless there is camera motion activity detected, since grive can take a while to perform a sync even if no files have changed. The sync script runs on a cron job that checks every minute to see if there are files to sync otherwise it does nothing. If syncing is required the script has a time delay since motion detection usually involves more than one photo and you don't want to do a sync for just one file if you can avoid it. This sync cron job allows the camera to run in parallel with grive syncing activity. Here is my "Almost Like Being There" video created with MeWiG from the stills. Not much activity these days.
https://www.youtube.com/watch?v=-igGzfY7uKs
This setup has been working like a Champ for several months, except for a slight problem for a day or two when google drive was having issues with syncing files from google down to my laptop (google drive internet files were OK so I knew RPI was successfully uploading files). Tried cleaning laptop files but eventually things mysteriously fixed themselves and no problems since.
GitHub - https://github.com/pageauc
YouTube - https://www.youtube.com/user/pageaucp

aardbei
Posts: 1
Joined: Sun May 04, 2014 9:23 pm

Re: Lightweight python motion detection

Sun May 04, 2014 9:38 pm

Hi,

Question. I am streaming the raspicam to an rtsp server and i would like
to use your script to check motion in that video stream.

What i did is change the command in the captureTestImage to a gstreamer command
what grabs an image from the video stream, convert it to jpeg and write it to /dev/stdout.
Problem is that it looks like the imageData is empty (at least the script stops there).

What am i doing wrong?


def captureTestImage():
# command = "raspistill -vf -hf -w %s -h %s -t 0 -e bmp -o -" % (100, 75)
command = "gst-launch-1.0 rtspsrc location=rtsp://192.168.4.170:80/live ! rtph264depay ! h264parse ! avdec_h264 ! videorate ! video/x-raw,framerate=1/1 ! videoconvert ! jpegenc ! queue ! filesink location=/dev/stdout"
imageData = StringIO.StringIO()
imageData.write(subprocess.check_output(command, shell=True))
imageData.seek(0)
im = Image.open(imageData)
buffer = im.load()
imageData.close()
return im, buffer

pageauc
Posts: 224
Joined: Fri Jan 04, 2013 10:52 pm

Re: Lightweight python motion detection

Fri May 23, 2014 11:48 pm

aardbei wrote:Hi,

Question. I am streaming the raspicam to an rtsp server and i would like
to use your script to check motion in that video stream.

What i did is change the command in the captureTestImage to a gstreamer command
what grabs an image from the video stream, convert it to jpeg and write it to /dev/stdout.
Problem is that it looks like the imageData is empty (at least the script stops there).

What am i doing wrong?

I believe the buffer file has to be an uncompressed format like bmp. jpeg is a lossy compressed format so pixel for pixel comparison won't work. The bmp format is uncompressed and allows the two buffer files to be compared pixel for pixel to calculate the number of changed pixels and if threshold exceeded then do something like take a larger photo as per the original script.


def captureTestImage():
# command = "raspistill -vf -hf -w %s -h %s -t 0 -e bmp -o -" % (100, 75)
command = "gst-launch-1.0 rtspsrc location=rtsp://192.168.4.170:80/live ! rtph264depay ! h264parse ! avdec_h264 ! videorate ! video/x-raw,framerate=1/1 ! videoconvert ! jpegenc ! queue ! filesink location=/dev/stdout"
imageData = StringIO.StringIO()
imageData.write(subprocess.check_output(command, shell=True))
imageData.seek(0)
im = Image.open(imageData)
buffer = im.load()
imageData.close()
return im, buffer
GitHub - https://github.com/pageauc
YouTube - https://www.youtube.com/user/pageaucp

Return to “Camera board”