tobrien81
Posts: 17
Joined: Thu Aug 30, 2012 9:57 am

Re: Lightweight python motion detection

Tue Jul 09, 2013 9:03 am

Hi

I have a curious one for you. I have "servoblaster" running on my Pi. When I so an insmod to initialise servoblaster the motion detect code here does not work :-( it just hangs at the "imageData.write(subprocess.check_output(command, shell=True))" line in the defined code "captureTestImage()". However if I reboot the Pi without initialising the servoblaster software it works just fine.

Any ideas?

Servoblaster software:
https://github.com/richardghirst/PiBits ... rvoBlaster

Regards
Tom O'Brien

User avatar
recantha2
Posts: 267
Joined: Wed Nov 14, 2012 9:34 am
Location: Potton, Bedfordshire
Contact: Website

Re: Lightweight python motion detection

Tue Jul 09, 2013 9:53 am

Quoting what I posted before:
I'm pleased to say that servoblaster _does_ work if the camera is plugged in. I talked to Richard who wrote servoblaster and between us we managed to work out what the problem is.

You need to edit the servoblaster source (servod.c), remove references to GPIO21 (pin P1-13) and recompile it. Then the problem doesn't happen. GPIO21 on a rev 2 board is actually GPIO27.
If I remove GPIO21 (pin P1-13) from servod.c and recompile, the problem doesn't happen.
GPIO21 on a rev 2 board is actually GPIO27 and this conflicts with the camera.
For if you struggle with the recompile, here's a basic guide to doing it:
http://www.raspberrypi.org/phpBB3/viewt ... er#p164500
--
Michael Horne - @recantha
Raspberry Pi blog - http://www.recantha.co.uk/blog

Cambridge Raspberry Jam
Website: http://camjam.me
Facebook: https://www.facebook.com/cambridgeraspberryjam
Follow the Cambridge Raspberry Jam on Twitter - @cambridgejam

tobrien81
Posts: 17
Joined: Thu Aug 30, 2012 9:57 am

Re: Lightweight python motion detection

Tue Jul 09, 2013 10:59 am

Hi

Sorry, I should have mentioned that I already tried this. However I only found one reference to GPIO21 in the servod.c file. Does that sound about right? It was in the "static uint8_c" section. Mine now looks like this:

static uint8_t servo2gpio[] = {
4, // P1-7
17, // P1-11
18, // P1-12
22, // P1-15
23, // P1-16
24, // P1-18
25, // P1-22
};

I then performed a "sudo make servod" at the command prompt followed by the following commands:

cd /home/pi/PiBits/ServoBlaster/
sudo insmod servoblaster.ko
sudo mknod -m 0666 /dev/servoblaster c 248 0

However the motion python script still isn't working. Have I missed something? I really appreciate your time and quick response :-)

User avatar
recantha2
Posts: 267
Joined: Wed Nov 14, 2012 9:34 am
Location: Potton, Bedfordshire
Contact: Website

Re: Lightweight python motion detection

Tue Jul 09, 2013 1:55 pm

That _sounds_ like what you've done is right. I should say that I never tried it with Motion, so perhaps it's a different problem. Sorry I can't be more help :-(
--
Michael Horne - @recantha
Raspberry Pi blog - http://www.recantha.co.uk/blog

Cambridge Raspberry Jam
Website: http://camjam.me
Facebook: https://www.facebook.com/cambridgeraspberryjam
Follow the Cambridge Raspberry Jam on Twitter - @cambridgejam

tobrien81
Posts: 17
Joined: Thu Aug 30, 2012 9:57 am

Re: Lightweight python motion detection

Tue Jul 09, 2013 11:43 pm

That's OK. Its not motion that I am using, sorry for the confusion. It is your python script that I just happened to name it motion :-)

Such a shame that it doesn't work. I might get onto the maker of servoblaster, might have a different insight perhaps?

Thanks again!!!

User avatar
recantha2
Posts: 267
Joined: Wed Nov 14, 2012 9:34 am
Location: Potton, Bedfordshire
Contact: Website

Re: Lightweight python motion detection

Wed Jul 10, 2013 6:28 am

Yeah, contact Richard (he's on the Forums) as he's always open to talking about issues with ServoBlaster.
--
Michael Horne - @recantha
Raspberry Pi blog - http://www.recantha.co.uk/blog

Cambridge Raspberry Jam
Website: http://camjam.me
Facebook: https://www.facebook.com/cambridgeraspberryjam
Follow the Cambridge Raspberry Jam on Twitter - @cambridgejam

rgh
Posts: 211
Joined: Fri Nov 25, 2011 3:53 pm

Re: Lightweight python motion detection

Wed Jul 10, 2013 5:16 pm

tobrien81 wrote:That's OK. Its not motion that I am using, sorry for the confusion. It is your python script that I just happened to name it motion :-)

Such a shame that it doesn't work. I might get onto the maker of servoblaster, might have a different insight perhaps?

Thanks again!!!
Hi, there are two implementations of servoblaster these days, as per the README, though you are not the only one to be confused by it :)

The original takes the form of a kernel module (servoblaster.ko) and the newer one runs as a user space daemon (servod). I recommend using servod these days as it does't need compiling against a specific kernel. It seems you have fixed the code of servod and then used the servoblaster.ko version.

So, make sure your old servoblaster.ko module is not loaded (rmmod servoblaster), then, after "make servod", simply do "sudo ./servod".

For others reading this, if you previously did a "make install_autostart" to make servoblaster.ko be loaded automatically on reboot, you need to undo that before you can start using servod. The easiest way to do that is probably to simply delete the "servoblaster" line from /etc/modules and "rmmod servoblaster". Note I don't provide a way to make servod start automatically on reboot at present, but there are lots of examples of how to do such things out there (earlier in this thread, for example, iirc).

Hope that helps.

chorlton2080
Posts: 124
Joined: Sun Dec 23, 2012 9:44 pm

Re: Lightweight python motion detection

Wed Jul 10, 2013 7:07 pm

To have this run automatically on boot:

Code: Select all

sudo nano /etc/rc.local
I have the motion detect python script in a "scripts" folder within the user space. So I would add the following before the last line (the exit 0):

Code: Select all

sudo python /home/pi/scripts/motiondetect.py
I don't think you need "sudo", but it doesn't do any harm to include it and at least it avoids one source of head-scratching when things don't happen as you expected. I use it because I've changed the script and it also looks at the GPIO pins.

Don't put it within the if....fi condition which may already be in your rc.local file and which checks for an IP address. If it is not connected to the network it your motion detect script may not then run.

This will then start on boot. You can enter/exit via SSH without affecting the python script.

I've also added a feature to email a warning to me on motion detection, with or without an image attachment of the cat which keeps triggering it. You can also connect a switch to one of the GPIO which are checked on boot to determine whether to run the script (or another).

tobrien81
Posts: 17
Joined: Thu Aug 30, 2012 9:57 am

Re: Lightweight python motion detection

Thu Jul 11, 2013 10:16 am

Wow! How much of a newb am I???? as soon as I unloaded the servoblaster module and ran the compiled servod script it WORKED!!!! Thanks so much :-)

Now, I just need to stop the image being shown on the screen each time motion is detected and then it will be seemless!
(any ideas?) I assume this is because of the "-o -" switch in raspistill?

Once again, thank you!!!

tobrien81

zeronickname
Posts: 13
Joined: Sat Jul 20, 2013 4:35 pm

Re: Lightweight python motion detection

Sat Jul 20, 2013 4:52 pm

I've modified the original script to auto upload the pictures to Picasa/Google Photos (taking advantage of the unlimited space by resizing the pictures to be < 2048px)

https://github.com/zeronickname/RasPiMotionDetect

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

Re: Lightweight python motion detection

Sun Jul 21, 2013 10:19 pm

brainflakes, your script is beautiful!
However, there where some bugs in the script and in the improvements of pageauc and peewee2.

# pictures are taken with width 1296 height 972 instead of saveWidth and saveHeight
# a preview image is shown when you have an open X-session
# "force capture" is not working any more in pageauc's script
# break of loop is not perfect in pageauc's script
# ..

I improved the script further more, for example it is now possible that not the whole image is scanned for changed pixel, but only some areas. this is usefull if you have trees in your picture which move like crazy when the wind blows. no image should be taken because the wind blows.

i will improve the script later, for example to upload the pictures to a server (but not on to Picasa/Google Photos)

here is the code so far:

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

import StringIO
import subprocess
import os
import time
from datetime import datetime
from PIL import Image

# 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 = 20
forceCapture = True
forceCaptureTime = 60 * 60 # Once an hour
filepath = "/home/pi/picam"
filenamePrefix = "capture"
diskSpaceToReserve = 40 * 1024 * 1024 # Keep 40 mb free on disk
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 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

# 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):
    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

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

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

# Get first image
image1, buffer1 = captureTestImage(cameraSettings, testWidth, testHeight)

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

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:
        if time.time() - lastCapture > forceCaptureTime:
            takePicture = True

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

    # Swap comparison buffers
    image1 = image2
    buffer1 = buffer2
Download the script and save it with the name "picam.py". If the script does not work at your pi, check if you copied it in linux-format (hint: LineFeed an not CarriageReturn + LineFeed). The script will not work if you have additional leading space-signs in the text (hint: check for space in line 1). You must make the script executeable before you run it (hint: "chmod +x picam.py" in terminal). Start the script by typing "./picam.py" in terminal or use the autostart-method described above.

Todo:
upload the script to github to prevent trouble with CarriageReturn+LineFeed and leading spaces
include file upload to linux-server by ssh instead of saving files on the pi (use ssh-keygen to prevent password-input):

Code: Select all

raspistill -o - | ssh [email protected] "cat >Path/To/Img/ImgName.jpg"
Edit / Uptdate: See http://www.raspberrypi.org/phpBB3/viewt ... 90#p394590 for a step-by-step instruction to get the script running.
Last edited by Kesthal on Sat Jul 27, 2013 3:36 pm, edited 1 time in total.

Pentala
Posts: 1
Joined: Sun Jul 21, 2013 10:29 pm

Re: Lightweight python motion detection

Sun Jul 21, 2013 10:33 pm

Hi all,

I've been tweaking this script for a specific application and have added the ability to use a mask to block out areas of the picture you don't want to check for motion detection. I've just got a couple of checks to run on the code but will upload the updated version as soon as possible.

Andy.

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

Re: Lightweight python motion detection

Mon Jul 22, 2013 6:46 am

Pentala, you have the same idea I had.

In my script (see above), I defined "Test-Areas" witch are checked for Motion.

The Whole image is:
testWidth = 100
testHeight = 75

With default settings, the whole image is checked:
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

If not the whole image should be checked, you can define areas, where the script should scan for changed pixel.
For example, if your picture looks like this:

OOOOXXXX
OOOOOOOO
OOOOOOOO

"O" 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]] ]

In area x=1 to 50, y is scanned from pixel 1 to 75. In area x=51 to 100, only y=26 to 75 is scanned. Area y=1 to 25 is not scanned in x=51 to 100!

kevpatts2
Posts: 8
Joined: Thu Jul 19, 2012 1:58 pm

Re: Lightweight python motion detection

Mon Jul 22, 2013 6:57 pm

Hey all,

I've just got this up and running andI really like it. I think there is one thing that I'd like it to do though, to make it a foolproof security camera. I'd like it to scp/sftp the files to a remote server, so that even if the camera itself is stolen I'll still have the pictures.

This is itself is not difficult, however I'd like it to do this without actually writing it first to the flash disk, therefore saving the write cycles on the flash disk. Is it possible to write them to a ram disk instead and then scp and delete, or pipe the output directly to the remote server?

My plan is to send them to a free Amazon EC2 instance.

Kevpatts

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

Re: Lightweight python motion detection

Mon Jul 22, 2013 8:51 pm

kevpatts2, raspistill can write to stdout, but scp can't receive data from std in. However, ssh will do the trick:

Code: Select all

raspistill -o - | ssh [email protected] "cat >Path/To/Img/ImgName.jpg"
You only have to change one line in the script, and disable the keepDiskSpaceFree-Command.

Try the command in the terminal first, if you have to enter a password, use ssh-keygen to generate a key.

Code: Select all

ssh-keygen -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
Just hit Enter when you are asked for to enter a passphrase.

You must run a cronjob on the remote server to delete old files.

Ask me again, if you have trouble to get it working.

kevpatts2
Posts: 8
Joined: Thu Jul 19, 2012 1:58 pm

Re: Lightweight python motion detection

Tue Jul 23, 2013 6:34 pm

Hey all, I'm very new to python, so having trouble getting the ssh to work.

I'm looking to use the ssh host from ~/.ssh/config

Code: Select all

...
threshold = 10
sensitivity = 180
forceCapture = True
forceCaptureTime = 60 * 60 # Once an hour
filepath = "~/stills"
filenamePrefix = "capture"
# File photo size settings
saveWidth = "1920"
saveHeight = "1080"
imageQuality = "15"
remoteHost = "ec2"
sshConfigFile = "/home/pi/.ssh/config"
diskSpaceToReserve = 400 * 1024 * 1024 # Keep 40 mb free on disk

#ssh = paramiko.SSHClient()
#sshConfig = f.open(sshConfigFile)
#ssh.parse(self,sshConfig)
#ssh.connect(remote)

# Capture a small test image (for motion detection)
def captureTestImage():
    command = "raspistill -w %s -h %s -t 0 -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 image to disk
def saveImage(width, height, 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)
    command = "raspistill -w "+saveWidth+" -h "+saveHeight+" -t 0 -e jpg -q "+imageQuality+" -o - | ssh "+remoteHost+":"+filename
    subprocess.call(command, shell=True)
    print "Captured %s" % filename
and I'm getting:

Code: Select all

ssh: Could not resolve hostname ec2:~/stills/capture-20130723-193038.jpg: Name or service not known
I've tried using ip address, -i and the private key and everything in the "command" variable, but I still get the same error. I've looked into paramiko also but don't know how to write the remote file with it.

Any help would be appreciated.

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

Re: Lightweight python motion detection

Tue Jul 23, 2013 7:34 pm

kevpatts2, first you should try if you can ssh to your remote server. On a terminal on the pi, type username is the name of your linux-account on the server, for example root or your name, servername can be a ip-address.
There are other methods to ssh to the server, e.g. use the ~/.ssh/config. But you must try it in the terminal if it works, you must be able to login without being asked to enter a passwort or a passphrase

If the first step works, type in the pi-terminal:
raspistill -o - | ssh [email protected] "cat >~/stills/test1.jpg"
The "[email protected]"-part must be the part which worked in step 1.
After this command, check if you get a error-message and check if you have a picture called test1.jpg in the ~/stills folder on your remote server. The folder ~/stills must exist on the remote server.

If this second step works, change one line in the script to:

Code: Select all

command = "raspistill -w "+saveWidth+" -h "+saveHeight+" -t 0 -e jpg -q "+imageQuality+" -o - | ssh "+remoteHost+" 'cat >"+filename+"'"
Your "remoteHost" variable must be set to the "[email protected]"-part that worked in step 1 and step 2

Try these steps an post all errors here.

kevpatts2
Posts: 8
Joined: Thu Jul 19, 2012 1:58 pm

Re: Lightweight python motion detection

Tue Jul 23, 2013 8:43 pm

Thanks Kesthal,

I had already checked that connectivity worked. The fix was the change of the command variable that you suggested. For some reason I was using scp notation instead of your ssh method. Working perfectly now.

Just another tip: on the remote server I've locked the "stills" folder (can create but can't delete files) by doing

Code: Select all

sudo chattr +a stills
This means that even if someone does compromise the the Raspi and successfully log into the remote host, they won't be able to delete the files.

Thanks for your help man.

The only other thing I'm looking for now os to get this running as a service/daemon so that it starts at boot. I'll start working on that soon.

Kevpatts

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

Re: Lightweight python motion detection

Tue Jul 23, 2013 9:09 pm

kevpatts2 wrote: The only other thing I'm looking for now os to get this running as a service/daemon so that it starts at boot. I'll start working on that soon.
Kevpatts
This is done using a init script which runs your picam.py code on boot and kills it during system shut down.

The Init-Script looks like this:

Code: Select all

### BEGIN INIT INFO
# Provides: picam
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: picam
# Description: picam
### END INIT INFO


#! /bin/sh
# /etc/init.d/picam


export HOME
case "$1" in
    start)
        echo "Starting picam"
        /home/pi/picam.py  2>&1 &
    ;;
    stop)
        echo "Stopping picam"
        CAM_PID=`ps auxwww | grep picam.py | grep -v grep | head -1 | awk '{print $2}'`
        kill -9 $CAM_PID
    ;;
    *)
        echo "Usage: /etc/init.d/picam {start|stop}"
        exit 1
    ;;
esac
exit 0
I uploaded this script to http://pastebin.com/jWbUME13 so you can download it from your pi:

1. On a terminal, type:

Code: Select all

wget -O - http://pastebin.com/raw.php?i=jWbUME13 | tr -d '\015' > ~/picam_init
Explaination for experts: The wget-command downloads the given URL, the "tr -d" deletes the Carriage Return because the script is in windows-format with CR LF instead of unix-format with just LF.

2. If your Picam-Python-Script is not in the folder /home/pi/picam.py, you should change /home/pi/picam.py to where-ever you are actually keeping the picam python script (line 20 and 24 in script)
To open the file in a editor, type in editor:

Code: Select all

nano ~/picam_init
Change the lines and save the file.

3. Move and rename this script into /etc/init.d/picam (you will need to use sudo to write to this directory)

Code: Select all

sudo mv ~/picam_init /etc/init.d/picam
4. Make the init script executable.

Code: Select all

sudo chmod +x /etc/init.d/picam
5. Make the picam init script known to the system by using the update-rc.d command.

Code: Select all

sudo update-rc.d picam defaults
Now on each boot the picam.py will automatically start on startup.

You can use the command

Code: Select all

/etc/init.d/picam start
or

Code: Select all

/etc/init.d/picam stop
to start or to stop the script manually.
Last edited by Kesthal on Sat Apr 19, 2014 11:57 pm, edited 2 times in total.

SourRon
Posts: 2
Joined: Fri Jul 26, 2013 2:40 pm

Re: Lightweight python motion detection

Fri Jul 26, 2013 2:51 pm

Hi Kesthal,

I am a noob to python (today is my first attempt) and have had a go at your script.

I have battled thro' the 'return outside function' errors, and the' unexpected indent' errors (my bad)
and am at a point where it says 'settings' is not defined.

I was wondering how you call/start the script. Are 'settings' parameters passed into the function ?

Could you show an example of how you call the script.

Also, I am interested in blocking out trees etc but cannot make out how to do this.

Can you explain further?
Thanks to everybody for all the work so far,
Sour Ron

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

Re: Lightweight python motion detection

Sat Jul 27, 2013 8:53 am

SourRon, I think you have some leading spaces in the script that prevent it to be able to execute. Or your script is not in linux-format.

To make is easy, I uploaded the script to http://pastebin.com/yH7JHz9w and here comes a step by step instruction to get it working on your pi:

1. Open a terminal on your pi. If you have a Keyboard and a Screen attached to your pi, just start your pi. If you see the command line, you have your terminal ready. If you see a graphical desktop, you must double click on the "Terminal"-Icon. You can also ssh from a remote computer to your pi. If you see a black screen and a prompt (e.g. "[email protected] ~ $"), you are ready with step 1.

2. You need to install PIL to run this script. Type

Code: Select all

sudo apt-get install python-imaging-tk
in the terminal window to do this.

3. Download the script to your pi. To do this, enter the following code in the terminal:

Code: Select all

wget -O - http://pastebin.com/raw.php?i=yH7JHz9w | tr -d '\015' > ~/picam.py
Explaination for experts: The wget-command downloads the given URL, the "tr -d" deletes the Carriage Return because the script is in windows-format with CR LF instead of unix-format with just LF.

4. Make the script executeable by typing:

Code: Select all

chmod +x ~/picam.py
5. Create the folder for the pictures:

Code: Select all

mkdir ~/picam
6. Start the script by typing:

Code: Select all

~/picam.py
the script is now running and taking pictures

7. To stop the script, hit the "STRG" and the "c"-key on the same time. in some cases, the "STRG"-Key is the "CTRL"-Key

8. You can adjust the setting of the script, e.g. if you want to flip your images (see cameraSettings in the script) or if you want to change the resolution of the saved pictures.
To open the script in an editor, type

Code: Select all

nano ~/picam.py
See the instructions on the bottom of the editor window to see how to use the nano editor.

9. If you want to prevent, that moving trees trigger your motion detection, you should set the variable debugMode in the script to value True. Open a editor (e.g. nano of step 8) and change line 66:
debugMode = True

Then start your script, wait until some pictures are saved, then stop the script. In your picture-folder, you will find a Bitmap-Picture called debug.bmp. Use this picture to determine, which pixel you want to exclude from your motion detection. Open this picture in a picture-viewer, zoom in, and count the pixel.
Read the lines 42 to 66 of the script to see how you have to adjust the variables testBorders and testAreaCount.

Save your changes in the script, start it, wait for some pictures, stop the script, and check the debug.bmp to see if you have choosen the right pixel.

When you are finished, set debugMode = False.

More description see above: http://www.raspberrypi.org/phpBB3/viewt ... 67#p391667

10. If you want to auto-start the script on system-boot, read the description above: http://www.raspberrypi.org/phpBB3/viewt ... 00#p392700

11. If you want to save the pictures on a remote unix-server, see the description above: http://www.raspberrypi.org/phpBB3/viewt ... 89#p392089 and http://www.raspberrypi.org/phpBB3/viewt ... 30#p392630
Line 84: subprocess.call("raspistill %s -w %s -h %s -t 200 -e jpg -q %s -n -o - | ssh [email protected] 'cat >%s'" % (settings, width, height, quality, filename), shell=True)
Disable keepDiskSpaceFree:
Line 81: # keepDiskSpaceFree(diskSpaceToReserve)

PS: sorry for bad english, auf Deutsch könnte ich alles viel besser erklären!

SourRon
Posts: 2
Joined: Fri Jul 26, 2013 2:40 pm

Re: Lightweight python motion detection

Sun Jul 28, 2013 2:46 pm

Hey Kesthal,

That was brilliant!
Thank you very much for the time and effort you have made in adding further comments.
I had to do a reinstall of the latest 'raspian' image on a new SD card (8g) as my old system was too small (2G).

I followed the instructions to the letter and every step went smoothly.
Only took about 10 minutes to do.
I have working script and am going to save the image to a network server.

Thank you once again,

kinda restores your faith in human nature... :D

Krisduck
Posts: 4
Joined: Thu Jun 06, 2013 6:14 am

Re: Lightweight python motion detection

Mon Jul 29, 2013 7:34 am

Is anyone else getting (mostly) green horizontal lines across their images? It's triggering the motion capture, so I've got a bunch of pics with green lines across them, but with no other movement. It seems like it might mostly be in lower-light situations, but I think there's been a few in brighter shots too. I'll try to keep an eye on it.

Cheers,

Kris

Nige C
Posts: 46
Joined: Thu Jul 19, 2012 12:22 am
Location: Hadleigh, Suffolk

Re: Lightweight python motion detection

Mon Jul 29, 2013 11:54 pm

This thread has been an insight to me. I received my Pi Camera Boards last week. I'm am a member of the Cloud Appreciation Society, this thread has really helped me. I want to monitor the great clouds around my locale right now with timelapse :)
Thank you everyone.
Retired power engineer with a lot of real life experience. Life is an adventure again :)

Nige C
Posts: 46
Joined: Thu Jul 19, 2012 12:22 am
Location: Hadleigh, Suffolk

Re: Lightweight python motion detection

Tue Jul 30, 2013 12:43 am

The one thing I do not need to record is blue sky, So no blue sky thinking here, by me :)
Retired power engineer with a lot of real life experience. Life is an adventure again :)

Return to “Camera board”