树莓派动作捕捉抓拍存储图像脚本

 更新时间:2019年06月22日 10:52:16   作者:soft2buy  
这篇文章主要为大家详细介绍了树莓派动作捕捉抓拍存储图像脚本,支持Python 2.7,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了树莓派动作捕捉抓拍存储图像的具体代码,供大家参考,具体内容如下

#!/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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 怎样用cmd命令行运行Python文件

    怎样用cmd命令行运行Python文件

    这篇文章主要介绍了怎样用cmd命令行运行Python文件问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Python列表和元组的定义与使用操作示例

    Python列表和元组的定义与使用操作示例

    这篇文章主要介绍了Python列表和元组的定义与使用操作,结合实例形式分析了Python中列表和元组的功能、区别、定义及使用方法,需要的朋友可以参考下
    2017-07-07
  • 跟老齐学Python之复习if语句

    跟老齐学Python之复习if语句

    是否记得,在上一部分,有一讲专门介绍if语句的:从if开始语句的征程。在学习if语句的时候,对python编程的基础知识了解的还不是很多,或许没有做什么太复杂的东西。本讲要对它进行一番复习,通过复习提高一下。如果此前有的东西忘记了,建议首先回头看看前面那讲。
    2014-10-10
  • Python压缩包处理模块zipfile和py7zr操作代码

    Python压缩包处理模块zipfile和py7zr操作代码

    目前对文件的压缩和解压缩比较常用的格式就是zip格式和7z格式,这篇文章主要介绍了Python压缩包处理模块zipfile和py7zr,需要的朋友可以参考下
    2022-06-06
  • Python Pandas数据分析工具用法实例

    Python Pandas数据分析工具用法实例

    这篇文章主要介绍了Python Pandas数据分析工具用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • python运行cmd命令行的3种方法总结

    python运行cmd命令行的3种方法总结

    虽然python在调用cmd命令方面使用的比较少,不过还是要用的,下面这篇文章主要给大家介绍了关于python运行cmd命令行的3种方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-09-09
  • Django model.py表单设置默认值允许为空的操作

    Django model.py表单设置默认值允许为空的操作

    这篇文章主要介绍了Django model.py表单设置默认值允许为空的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • Python交换字典键值对的四种方法实例

    Python交换字典键值对的四种方法实例

    字典中有成对出现的键和值,但是字典中的键值对不是都能修改的,只有值才能修改,下面这篇文章主要给大家介绍了关于Python交换字典键值对的四种方法,需要的朋友可以参考下
    2022-12-12
  • Python OpenCV学习之图像形态学

    Python OpenCV学习之图像形态学

    形态学处理方法是基于对二进制图像进行处理的,卷积核决定图像处理后的效果。本文将为大家详细介绍一下OpenCV中的图像形态学,感兴趣的可以了解一下
    2022-01-01
  • 一文带你深入了解Python中的GeneratorExit异常处理

    一文带你深入了解Python中的GeneratorExit异常处理

    GeneratorExit是Python内置的异常,当生成器或协程被强制关闭时,Python解释器会向其发送这个异常,下面我们来看看如何处理这一异常吧
    2025-03-03

最新评论