bdalton
Posts: 4
Joined: Fri Jan 02, 2015 9:18 pm

Re: Lightweight python motion detection

Wed Jan 14, 2015 8:27 pm

I'll have to try that next time. Thanks for the tip.

lbendlin
Posts: 7
Joined: Mon Jan 07, 2013 6:51 pm
Location: MA, USA

Re: Lightweight python motion detection

Sun Jan 25, 2015 11:20 pm

My Pi camera is pointing out to the road in front of our house. I am curious if I could use the rough motion vectors to count the cars going in either direction. They already trigger the motion sensor, but since cars normally travel horizontally I was wondering if I could simplify the motion detect code and just use the X values instead of the Pythagoras thing. Is it possible to somehow create a video that shows the motion vectors instead of the real thing?

Another problem I have is that my circular buffer has much more than the 10 seconds of video that I requested for each file (5 seconds before motion and 5 seconds after). I know it's just an estimated number but I very often get recordings of the last two minutes with that setting. Is there a way to trim the circular buffer before writing the stream to file?

rollerrolol
Posts: 8
Joined: Sat Feb 07, 2015 10:12 pm

Re: Lightweight python motion detection

Sat Feb 07, 2015 10:17 pm

I would like to be able to use motion detection, but also view the camera almost-live from a simple webpage, for example once per minute. I would need a photo to be taken each minute which isn't uploaded to gdrive, but moved to /var/www. How can I achieve this? For me it would be enough if the "forcecapture" image would have a different name. Then I can move that file easily.

MrGuy
Posts: 1
Joined: Wed Mar 11, 2015 4:16 pm

Re: Lightweight python motion detection

Wed Mar 11, 2015 4:28 pm

pageauc wrote:pi-timolo
I have also included a pi-motion-lite for those who want a minimal picamera library python motion detection script for projects.
http://www.raspberrypi.org/forums/viewt ... 03#p657803
Regards Claude ...
Sweet! I've been playing with your pi-motion-lite file and have learned a lot. It's been extremely helpful. I have one small recommendation: force it to get a new stream1 image every so often.. something like this:

Code: Select all

    while True:
        stream2 = getStreamImage(dayTime)
        if checkForMotion(stream1, stream2):
            userMotionCode()
            Cycle = Cycle + 1
            if Cycle >= 10:
                print ("10 Cycles completed..")
                Cycle = 0
                stream1 = getStreamImage(dayTime) #get fresh image so it doesn't keep dumping pictures due to pixel difference
            stream2 = stream1
        stream2 = stream1
    return
If the camera is near a window it will be up the slightest light changes from outside and continue to dump pictures because it's constantly references that first stream1 image.

darkdaniel100
Posts: 1
Joined: Fri Apr 03, 2015 9:36 pm

Re: Lightweight python motion detection

Fri Apr 03, 2015 9:42 pm

Not really being a Python expert - Where in the pi-timolo.py file would you need to add this code? I am guessing you would need to make some changes to your code before it would work?
MrGuy wrote:
pageauc wrote:pi-timolo
I have also included a pi-motion-lite for those who want a minimal picamera library python motion detection script for projects.
http://www.raspberrypi.org/forums/viewt ... 03#p657803
Regards Claude ...
Sweet! I've been playing with your pi-motion-lite file and have learned a lot. It's been extremely helpful. I have one small recommendation: force it to get a new stream1 image every so often.. something like this:

Code: Select all

    while True:
        stream2 = getStreamImage(dayTime)
        if checkForMotion(stream1, stream2):
            userMotionCode()
            Cycle = Cycle + 1
            if Cycle >= 10:
                print ("10 Cycles completed..")
                Cycle = 0
                stream1 = getStreamImage(dayTime) #get fresh image so it doesn't keep dumping pictures due to pixel difference
            stream2 = stream1
        stream2 = stream1
    return
If the camera is near a window it will be up the slightest light changes from outside and continue to dump pictures because it's constantly references that first stream1 image.

robomaster
Posts: 1
Joined: Sun May 10, 2015 6:29 am

Re: Lightweight python motion detection

Sun May 10, 2015 7:15 am

Hi, This is very good script . However, when I run it, it does not return from the imageDataWrite(subprocess call during the first captureTestImage() call. It hangs there until I hit crtl c. How can I fix this? Does it matter if I don't have the tty0AM0 setup? Thanks.

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Fri May 15, 2015 9:07 pm

Quick request...

I'm new to Pi and just getting under way. Given that I'm playing Catch-up on this thread can anyone help out on where to start?
  1. What is current version of Killagregs work? Is it all in one file here or somewhere on github, etc..??
  2. Are there any docs on what I need to install (apt-get etc...) like VLC and other stuff both apps and scripts it may require?

spikedrba
Posts: 75
Joined: Fri Feb 28, 2014 2:19 am

Re: Lightweight python motion detection

Fri May 15, 2015 9:41 pm

wirelessguyny wrote:Quick request...

I'm new to Pi and just getting under way. Given that I'm playing Catch-up on this thread can anyone help out on where to start?
  1. What is current version of Killagregs work? Is it all in one file here or somewhere on github, etc..??
  2. Are there any docs on what I need to install (apt-get etc...) like VLC and other stuff both apps and scripts it may require?
I can offer a simplified cleaned up version (no snapshot, some added and some removed debugging stuff) here:

https://gist.github.com/spikedrba/aecb82d8b51e991dbd01

notice I'm doing some work where I require a lot of fps, so that's cranked up to 45, not your usual 25-30.

as to what to install, just apt-get install python-numpy python-picamera python-imaging and you'll be set. No vlc or anything else, it's a pure python implementation with no external dependencies. If you ever want to conver those h264 videos into mp4 for easier playback apt-get install gpac and look up http://gpac.wp.mines-telecom.fr/mp4box/

hope that helps,

Spike

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Fri May 15, 2015 10:06 pm

Excellent. Thanks.

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Mon May 18, 2015 3:50 pm

OK, time for more questions. :)

I've gotten the python script installed but wasn't quite sure about how things are loading up. I'm running "sudo python pmd.py &" manually whihc throws the process in to the background. When it launches it give me a PID... however it seems that a second is created as well. When I kill that process I see that there is another python pmd.py running (which I think it actually the real one since the LED goes off when I kill that one).

1. How are others running this process?

2. I think I have the sensitivity to a good range but I am noticing that the placement of my camera doesn't give the best results. Is there an app or config anyone is using to tweak the color/brightness settings on the camera?

Thanks.

spikedrba
Posts: 75
Joined: Fri Feb 28, 2014 2:19 am

Re: Lightweight python motion detection

Mon May 18, 2015 5:35 pm

ok, first thing first, while I started out with that script I linked you before, there's also one that the author of picamera posted which is a very nice example with comments that might help you understand what's going on with the code:

https://gist.github.com/waveform80/9e990f56dabe27b42bfb

As per comments to that gist there seems to be some problems that have yet to be figured out. Also you might find reading through this issue useful:

https://github.com/waveform80/picamera/issues/215

Back to the other script and your questions:
- you don't need to run it as sudo, pi user will do
- the script will simply create a new video file .h264 in the specified directory when motion is detected
- regarding having two processes, I'm not sure what's going on, I only get one as I'd expect to. Can you be more specific about all the steps you take?
- as to how I run this process, right now I'm doing the same thing you do using rc.local. this is ugly and long term I want a proper init.d script with an actual watchdog to restart the script if it dies, etc. Making things more robust is the objective of the security camera project I'm working on
- I'm not sure what you mean with your second question, what's "best results"? also in what conditions? the way the script does motion detection is actually very simple, another thing I'm trying to improve upon so depending on the environment and the sensitivity levels you can expect a lot of false positives (for example in my case recording outdoor with grass/trees moving I have a lot of noise to filter out).

hope that helps,

Spike

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Mon May 18, 2015 9:06 pm

Spike.

So it seems the "$ sudo python pmd.py &" spawns two processes. I tried removing the sudo as you suggested using just "$ python pmd.py &" and things look fine. I suppose running is as the local user is perhaps safer as well.

Question: If I execute the command and let it record normally what happens when the data card is full? I wasn't sure if you implemented anything that deletes the oldest stuff when the SD card is near full and allows it to keep looping.

My other question before was actually about modifying the cameras settings. I ended up adding a line in to the script to specify

Code: Select all

camera.exposure_mode = 'backlight' 
because things were way too dark on my original streams. I will attempt changing that to AUTO but whatever the camera had as its original defaults were just plain off.

spikedrba
Posts: 75
Joined: Fri Feb 28, 2014 2:19 am

Re: Lightweight python motion detection

Mon May 18, 2015 10:35 pm

wirelessguyny wrote:Spike.
Question: If I execute the command and let it record normally what happens when the data card is full? I wasn't sure if you implemented anything that deletes the oldest stuff when the SD card is near full and allows it to keep looping.
this is another of those improvements we are working on. We've decided to implement a little python daemon (using python-daemon) that amognst other things monitor disk space and purges things as configured/needed after moving them off elsewhere if that's the desired behavior (long term we're aiming to sync to samba shares, dropbox etc). As of right now I just have a simple bash one liner that deletes anything older than 48hrs (this obviously depends on size of sd card and amount of recording, but fits my bill).

since you mentioned the SD card, be aware that repeated writes will relatively quickly destroy the card. There's a bunch fo things that can be done, but in our case, since we want the camera to be autonomous, we're attaching a SSD disk to it.
wirelessguyny wrote:My other question before was actually about modifying the cameras settings. I ended up adding a line in to the script to specify

Code: Select all

camera.exposure_mode = 'backlight' 
because things were way too dark on my original streams. I will attempt changing that to AUTO but whatever the camera had as its original defaults were just plain off.
AUTO should be default, weird that it was so much off, haven't seen it before, but I guess it depends on the environment.

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Tue May 19, 2015 9:03 pm

Interesting note there about the Micro SD card. I'm not sure that SSD is truly within the budget for myself or most folks. Unless you've had luck with using USB Key fobs. (Either way an externally powered multi-TB USB ext enclosure is likely less than the cost of a 128 or 256gb SSD).

Is there a performance hit in writing data to USB rather than the internal MicroSD?
How about trying to offload/FTP from the SSD/ext HD while Motion Capture is still running. Any idea on CPU drain, poss issues??

(PS - I'd be interested in the Python Daemon script. Pls forward URL details or PM me if you like).

Thanks.

spikedrba
Posts: 75
Joined: Fri Feb 28, 2014 2:19 am

Re: Lightweight python motion detection

Wed May 20, 2015 9:07 pm

wirelessguyny wrote:Interesting note there about the Micro SD card. I'm not sure that SSD is truly within the budget for myself or most folks. Unless you've had luck with using USB Key fobs. (Either way an externally powered multi-TB USB ext enclosure is likely less than the cost of a 128 or 256gb SSD).
sure, that'd work the same, the SSD disk would still go through an SSD adaptor and given the amount of data you'd be writing the speed of SSD isn't needed. Main issue would be power for a big multi-TB disk, you would probably need a powered usb hub.
wirelessguyny wrote: Is there a performance hit in writing data to USB rather than the internal MicroSD?
not that I know of, no, only thing to keep in mind as I already mentioned is that USB shares bus with ethernet.
wirelessguyny wrote:How about trying to offload/FTP from the SSD/ext HD while Motion Capture is still running. Any idea on CPU drain, poss issues??
see above, writing to USB and to the network will be a problem if you're pushing a lot of MBs, but should be ok under most circumstances.
wirelessguyny wrote: (PS - I'd be interested in the Python Daemon script. Pls forward URL details or PM me if you like).
working on it, would you like to contribute some code? :)

Thanks.[/quote]

lucas.johnson
Posts: 1
Joined: Fri May 22, 2015 10:37 am

Re: Lightweight python motion detection

Fri May 22, 2015 11:26 am

Hi,
I pretty new to the world of Pi, can someone please help I am trying to run this code when the Pi boots however I am having issues when trying to run the script from terminal. I don't know if the "chmod" command I am issuing is incorrect or if it is something to do with the script.

Can anyone help with the commands to make this script executable?

Many thanks.

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Tue Jun 02, 2015 2:32 am

The pmd.py file does not need ot be executable. At least it's not set up that way on my Pi right now. I just run

Code: Select all

 python pmd.py 
In order for this to load correctly you must configure the file a bit first. If you haven't done that run

Code: Select all

sudo nano pmd.py
You'll need to define the directory where the files wil be stored at a minimum.

If you have any more details on where your issue may lie let us know.

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Tue Jun 02, 2015 3:47 am

I'm making a bit of progress and thought I'd share some details with the group.

Spike mentioned previously that there seem to be issues with trying to constantly write to an SD card. Here is how I set up a USB drive to work with my Pi and camera.

Pre-req: If ntfs support is not yet installed run

Code: Select all

sudo apt-get install ntfs-3g
Step 1: Name your target:

Code: Select all

sudo mkdir /media/USBDRIVE
sudo chmod 770 /media/USBDRIVE/
Step 2:
Find the drive you've just connected…

Code: Select all

ls -l /dev/disk/by-uuid/
Write the UUID Down. It looks something like 1XPIBIE6BEEZB456 and will likely be on /../sda1

You can test things mounting the drive manually with:

Code: Select all

sudo mount -t ntfs-3g -o uid=1000,gid=1000,umask=007 /dev/sda1 /media/USBDRIVE
and then

Code: Select all

sudo umount /media/USBDRIVE
Note:
ntfs-3g for NTFS Drives
vfat for FAT32 Drives
ext4 for ext4 Drives

Step 3:
Next you want to edit your fstab file so that the device is loaded whenever it is connected. Run...

Code: Select all

sudo cp /etc/fstab /etc/fstab.backup
then

Code: Select all

sudo nano /etc/fstab
Add this line to the bottom using YOUR UUID and save your file:

Code: Select all

UUID=1XPIBIE6BEEZB456   /media/USBDRIVE ntfs-3g defaults,auto,umask=000,users,rw 0 0
Step 5:
You can test if this works by running

Code: Select all

mount -a
This should automatically mount anything in your fstab file. Try to get to that location

Code: Select all

cd /media/USBDRIVE
if it doesn't fail you've got it!!!

If successful you can go in to your pmd.py file and alter your filepath to your new location.

**Note: By using the UUID as we've done here your drive will get the same mount point (/media/USBDRIVE) irregardless of which USB port you later plug it in to.

spikedrba
Posts: 75
Joined: Fri Feb 28, 2014 2:19 am

Re: Lightweight python motion detection

Tue Jun 02, 2015 3:42 pm

grea progress @wirelessguy. For the sake of clarity I wanted to elaborate on "there seems to be issues writing to the SD card". The issue is the same one that affected SSD drives a while back before Trim operation was introduced. In the SD world some cards will support what is called "Wear leveling", which basically means the electronics will try to spread the writes. If that isn't supported then there's a certain likelihood that the same areas will be written over and over again, wearing those sectors out. As the OS doesn't know about it it will eventually choke as the hardware returns I/O errors.

wirelessguyny
Posts: 15
Joined: Fri May 15, 2015 8:48 pm

Re: Lightweight python motion detection

Wed Jul 08, 2015 7:21 pm

I've started testing my configuration and have run in to some sort of snag. I'm not sure if anyone else is experiencing anything similar.

I created a shell script to load the camera during startup and then added an entry in to crontab so that the camera automatically restarts at reboot. I had been troubleshooting some permissions issues (root versus pi user) with regards to the base OS versus the USB drive I have installed.

anyhow... in the process of my work today I ran a sudo apt-get update (and upgrade) and now nothing works. :(

If anyone has any troubleshooting suggestions I'd appreciate the help as I'm not an expert in this domain. It looks like sudo raspi-config is not enabling the camera :( At least that's what my cronlog file is telling me. I can't run raspistill as it says the same thing. I atttempted to look at the /usr/bin raspi-config file in the hopes of figuring out the command line it runs to enable the camera but it's not something I readily understand.

For now I'm sunk .

I suppose there is a chance that when I moved the pi unit around the cable came loose in the case but it's mount pretty well and would take me some effort to disassemble. My thought is that this is a software problem and I'd refer to hunt that down than tearing everything apart just to confirm that nothing was jostled internally.

so... consider this my WARNING Currently running an apt-get update could hose your camera settings. I'm not 100% sure. I don't know how to back out updates so for now I'm on standby until a solution presents itself. I'l keep the group updated here in case this is either user error or an issue everyone may face.

All the best.

rob+pi
Posts: 15
Joined: Fri Jan 11, 2013 12:17 am

Save your files to Dropbox

Mon Jul 20, 2015 7:18 pm

regarding the saving of an unknown number of images to the SD card or a USB drive I opted for filling up a free Dropbox account. I can view the images on the Dropbox app on my phone.
Great article at rasp.tv about setting up a Dropbox app that could write files from the Pi.
http://raspi.tv/2013/how-to-use-dropbox ... spberry-pi

It is fairly straight forward, log in to your Dropbox account, visit the developers pages and create an entry for a new application that has file access and copy down the secret keys. Then install a bash script from https://github.com/andreafabrizi/Dropbox-Uploader and enter the keys.

apl4
Posts: 2
Joined: Fri Feb 12, 2016 7:09 am

Re: Lightweight python motion detection

Mon Feb 29, 2016 11:25 am

I am unable to test this at the moment (away from my pi), but is anyone able to test whether this would be able to distinguish between the change in colour of an led indicator.
I want to detect, with time and date, when an led indicator on a heating controller indicates a fault. So there is no movement, only the colour change

cmegens
Posts: 28
Joined: Fri May 24, 2013 12:23 pm
Location: Netherlands

Re: Lightweight python motion detection

Thu Mar 17, 2016 4:09 pm

killagreg wrote:Hi,
inspired by this nice disscussion and code examples I have written a similar script for a surveillance job.
It combines also some the advanced techniques of picamera 1.8 into the game.

I hope you enjoy that.

Regards Greg

Code: Select all

#!/usr/bin/python

# This script implements a motion capture surveillace cam for raspery pi using picam.
# It uses the motion vecors magnitude of the h264 hw-encoder to detect motion activity.
# At the time of motion detection a jpg snapshot is saved together with a h264 video stream
# some seconds before, during and after motion activity to the 'filepath' directory.

import os
import subprocess
import io
import picamera
import picamera.array
import numpy as np
import datetime as dt
import time

#seup filepath for motion capure data
filepath = '/home/pi/motion/video'
# setup pre and post video recording around motion event
video_preseconds = 3
video_postseconds = 3
#setup video/snapshot resolution
video_width = 640#1280
video_height = 480#720
#setup video rotation (0, 90, 180, 270)
video_rotation = 180

# setup motion detection threshold, i.e. magnitude of a motion block to count as  motion
motion_threshold = 60
# setup motion detection sensitivity, i.e number of motion blocks that trigger a motion detection
motion_sensitivity = 10



# do not change code behind that line
#--------------------------------------
motion_detected = False
motion_timestamp = time.time()

#call back handler for motion output data from h264 hw encoder
class MyMotionDetector(picamera.array.PiMotionAnalysis):
    def analyse(self, a):
        global motion_detected, motion_timestamp
        # calcuate length of motion vectors of mpeg macro blocks
        a = np.sqrt(
            np.square(a['x'].astype(np.float)) +
            np.square(a['y'].astype(np.float))
            ).clip(0, 255).astype(np.uint8)
        # If there're more than 10 vectors with a magnitude greater
        # than 60, then say we've detected motion
        th = ((a > motion_threshold).sum() > motion_sensitivity)
        now = time.time()
        # motion logic, triger on motion and stop after 2 seconds of inactivity
        if th:
                motion_timestamp = now

        if motion_detected:
                if (now - motion_timestamp) >= video_postseconds:
                        motion_detected = False
        else:
                if th:
                        motion_detected = True



def write_video(stream):
    # Write the entire content of the circular buffer to disk. No need to
    # lock the stream here as we're definitely not writing to it
    # simultaneously
    global motion_filename

    with io.open(motion_filename + '-before.h264', 'wb') as output:
        for frame in stream.frames:
            if frame.frame_type == picamera.PiVideoFrameType.sps_header:
                stream.seek(frame.position)
                break
        while True:
            buf = stream.read1()
            if not buf:
                break
            output.write(buf)
    # Wipe the circular stream once we're done
    stream.seek(0)
    stream.truncate()


os.system('clear')
print "Motion Detection"
print "----------------"
print "                "
with picamera.PiCamera() as camera:
    camera.resolution = (video_width, video_height)
    camera.framerate = 25
    camera.rotation = video_rotation
    camera.video_stabilization = True
    camera.annotate_background = True
    # setup a circular buffer
    stream = picamera.PiCameraCircularIO(camera, seconds = video_preseconds)
    # hi resolution video recording into circular buffer from splitter port 1
    camera.start_recording(stream, format='h264', splitter_port=1)
    #camera.start_recording('test.h264', splitter_port=1)
    # low resolution motion vector analysis from splitter port 2
    camera.start_recording('/dev/null', splitter_port=2, resize=(340,240) ,format='h264', motion_output=MyMotionDetector(camera, size=(340,240)))
    # wait some seconds for stable video data
    camera.wait_recording(1, splitter_port=1)
    motion_detected = False

    print "Motion Capture ready!"
    try:
        while True:
                # motion event must trigger this action here
                camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                if motion_detected:
                        print "Motion detected: " , dt.datetime.now()
                        motion_filename = filepath + "/" + time.strftime("%Y%m%d-%H%M%S", time.gmtime(motion_timestamp))
                        camera.split_recording(motion_filename + '-after.h264', splitter_port=1)
                        # catch an image as video preview during video recording (uses splitter port 0) at time of the motion event
                        camera.capture(motion_filename + '.jpg', use_video_port=True)
                        # save circular buffer before motion event
                        write_video(stream)
                        #wait for end of motion event here
                        while motion_detected:
                                camera.annotate_text = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                                camera.wait_recording(1, splitter_port=1)
                        #split video recording back in to circular buffer
                        camera.split_recording(stream, splitter_port=1)
                        subprocess.call("cat %s %s > %s && rm -f %s" % (motion_filename + "-before.h264", motion_filename + "-after.h264", motion_filename + ".h264", motion_filename + "-*.h264"), shell=True)
                        print "Motion stopped:" , dt.datetime.now()


    finally:
        camera.stop_recording(splitter_port=1)
        camera.stop_recording(splitter_port=2)
Can't seem to get this working? I get a nice screen saying



Motion Detection
----------------

Motion Capture ready!

but no video or anything is stored to /home/pi/motion/video

Gave all the write access to that folder, but no luck...

dossn
Posts: 1
Joined: Sun May 01, 2016 7:05 am

Re: Lightweight python motion detection

Mon May 02, 2016 4:48 am

Hi All
I was wondering if anyone had any luck implementing a ftp upload for each time the pi detects motion.
I'm running this script and i have got no idea on how to implement a ftp upload.
Any help would be greatly appreciated.

Nick

Code: Select all

#!/usr/bin/python
#
#     Lightweight Motion Detection using python picamera libraries
#        based on code from raspberry pi forum by user utpalc
#        modified by Claude Pageau for this working example
#     ------------------------------------------------------------
# original code on github https://github.com/pageauc/picamera-motion

# This is sample code that can be used for further development

verbose = True
if verbose:
    print "Loading python libraries ....."
else:
    print "verbose output has been disabled verbose=False"

import picamera
import picamera.array
import datetime
import time
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from fractions import Fraction

#Constants
SECONDS2MICRO = 1000000  # Constant for converting Shutter Speed in Seconds to Microseconds

# User Customizable Settings
imageDir = "images"
imagePath = "/home/pi/pimotion/" + imageDir
imageNamePrefix = 'capture-'  # Prefix for all image file names. Eg front-
imageWidth = 1980
imageHeight = 1080
imageVFlip = False   # Flip image Vertically
imageHFlip = False   # Flip image Horizontally
imagePreview = False

numberSequence = False

threshold = 10  # How Much pixel changes
sensitivity = 100  # How many pixels change

nightISO = 800
nightShutSpeed = 6 * SECONDS2MICRO  # seconds times conversion to microseconds constant

# Advanced Settings not normally changed 
testWidth = 100
testHeight = 75

def checkImagePath(imagedir):
    # Find the path of this python script and set some global variables
    mypath=os.path.abspath(__file__)
    baseDir=mypath[0:mypath.rfind("/")+1]
    baseFileName=mypath[mypath.rfind("/")+1:mypath.rfind(".")]

    # Setup imagePath and create folder if it Does Not Exist.
    imagePath = baseDir + imagedir  # Where to save the images
    # if imagePath does not exist create the folder
    if not os.path.isdir(imagePath):
        if verbose:
            print "%s - Image Storage folder not found." % (progName)
            print "%s - Creating image storage folder %s " % (progName, imagePath)
        os.makedirs(imagePath)
    return imagePath

def takeDayImage(imageWidth, imageHeight, filename):
    if verbose:
        print "takeDayImage - Working ....."
    with picamera.PiCamera() as camera:
        camera.resolution = (imageWidth, imageHeight) 
        # camera.rotation = cameraRotate #Note use imageVFlip and imageHFlip variables
        if imagePreview:
            camera.start_preview()
        camera.vflip = imageVFlip
        camera.hflip = imageHFlip
        # Day Automatic Mode
        camera.exposure_mode = 'auto'
        camera.awb_mode = 'auto'
        camera.capture(filename)
    if verbose:  
        print "takeDayImage - Captured %s" % (filename)
    return filename

def takeNightImage(imageWidth, imageHeight, filename):
    if verbose:
        print "takeNightImage - Working ....."
    with picamera.PiCamera() as camera:
        camera.resolution = (imageWidth, imageHeight) 
        if imagePreview:
            camera.start_preview()
        camera.vflip = imageVFlip
        camera.hflip = imageHFlip
        # Night time low light settings have long exposure times 
        # Settings for Low Light Conditions 
        # Set a frame rate of 1/6 fps, then set shutter
        # speed to 6s and ISO to approx 800 per nightISO variable
        camera.framerate = Fraction(1, 6)
        camera.shutter_speed = nightShutSpeed
        camera.exposure_mode = 'off'
        camera.iso = nightISO
        # Give the camera a good long time to measure AWB
        # (you may wish to use fixed AWB instead)
        time.sleep(10)
        camera.capture(filename)
    if verbose:  
        print "checkNightMode - Captured %s" % (filename)
    return filename

def takeMotionImage(width, height, daymode):
    with picamera.PiCamera() as camera:
        time.sleep(1)
        camera.resolution = (width, height)
        with picamera.array.PiRGBArray(camera) as stream:
            if daymode:
                camera.exposure_mode = 'auto'
                camera.awb_mode = 'auto' 
            else:
                # Take Low Light image            
                # Set a framerate of 1/6 fps, then set shutter
                # speed to 6s and ISO to 800
                camera.framerate = Fraction(1, 6)
                camera.shutter_speed = nightShutSpeed
                camera.exposure_mode = 'off'
                camera.iso = nightISO
                # Give the camera a good long time to measure AWB
                # (you may wish to use fixed AWB instead)
                time.sleep( 10 )
            camera.capture(stream, format='rgb')
            return stream.array

def scanIfDay(width, height, daymode):
    data1 = takeMotionImage(width, height, daymode)
    while not motionFound:
        data2 = takeMotionImage(width, height, daymode)
        pCnt = 0L;
        diffCount = 0L;
        for w in range(0, width):
            for h in range(0, height):
                # get the diff of the pixel. Conversion to int
                # is required to avoid unsigned short overflow.
                diff = abs(int(data1[h][w][1]) - int(data2[h][w][1]))
                if  diff > threshold:
                    diffCount += 1
            if diffCount > sensitivity:
                break; #break outer loop.
        if diffCount > sensitivity:
            motionFound = True
        else:
            # print "Sum of all pixels=", pxCnt
            data2 = data1              
    return motionFound
           
def scanMotion(width, height, daymode):
    motionFound = False
    data1 = takeMotionImage(width, height, daymode)
    while not motionFound:
        data2 = takeMotionImage(width, height, daymode)
        diffCount = 0L;
        for w in range(0, width):
            for h in range(0, height):
                # get the diff of the pixel. Conversion to int
                # is required to avoid unsigned short overflow.
                diff = abs(int(data1[h][w][1]) - int(data2[h][w][1]))
                if  diff > threshold:
                    diffCount += 1
            if diffCount > sensitivity:
                break; #break outer loop.
        if diffCount > sensitivity:
            motionFound = True
        else:
            data2 = data1              
    return motionFound

def getFileName(imagePath, imageNamePrefix, currentCount):
    rightNow = datetime.datetime.now()
    if numberSequence :
        filename = imagePath + "/" + imageNamePrefix + str(currentCount) + ".jpg"
    else:
        filename = "%s/%s%04d%02d%02d-%02d%02d%02d.jpg" % ( imagePath, imageNamePrefix ,rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second)
    return filename    

def motionDetection():
    print "Scanning for Motion threshold=%i sensitivity=%i ......"  % (threshold, sensitivity)
    isDay = True
    currentCount= 1000
    while True:
        if scanMotion(testWidth, testHeight, isDay):
            filename = getFileName(imagePath, imageNamePrefix, currentCount)
            if numberSequence:
                currentCount += 1
            if isDay:
                takeDayImage( imageWidth, imageHeight, filename )
            else:
                takeNightImage( imageWidth, imageHeight, filename )
             
if __name__ == '__main__':
    try:
        motionDetection()
    finally:
        print ""
        print "+++++++++++++++"
        print "Exiting Program"
        print "+++++++++++++++" 
        print ""        

    
    
    

mazhar897
Posts: 11
Joined: Sat Mar 19, 2016 1:23 am

Re: Lightweight python motion detection

Sun Jun 19, 2016 8:50 am

Is there any way I can use this code to get the position/ coordinates of the highest change in pixels between two frames

Return to “Camera board”