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


Posted in Python onJune 22, 2019

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

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

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

Python 相关文章推荐
在 Django/Flask 开发服务器上使用 HTTPS
Jul 03 Python
python字符串替换的2种方法
Nov 30 Python
用Python从零实现贝叶斯分类器的机器学习的教程
Mar 31 Python
使用Python脚本来获取Cisco设备信息的示例
May 04 Python
matplotlib绘制符合论文要求的图片实例(必看篇)
Jun 02 Python
python中for循环输出列表索引与对应的值方法
Nov 07 Python
pandas的连接函数concat()函数的具体使用方法
Jul 09 Python
python通过robert、sobel、Laplace算子实现图像边缘提取详解
Aug 21 Python
Python range与enumerate函数区别解析
Feb 28 Python
Python猜数字算法题详解
Mar 01 Python
python给list排序的简单方法
Dec 10 Python
5分钟快速掌握Python定时任务框架的实现
Jan 26 Python
python+openCV利用摄像头实现人员活动检测
Jun 22 #Python
树莓派实现移动拍照
Jun 22 #Python
树莓派+摄像头实现对移动物体的检测
Jun 22 #Python
Python数据结构与算法(几种排序)小结
Jun 22 #Python
python+opencv实现摄像头调用的方法
Jun 22 #Python
python算法与数据结构之冒泡排序实例详解
Jun 22 #Python
分析运行中的 Python 进程详细解析
Jun 22 #Python
You might like
php中定义网站根目录的常用方法
2010/08/08 PHP
解析php中mysql_connect与mysql_pconncet的区别详解
2013/05/15 PHP
php启用sphinx全文搜索的实现方法
2014/12/24 PHP
php简单截取字符串代码示例
2016/10/19 PHP
php 广告点击统计代码(php+mysql)
2018/02/21 PHP
prototype Element学习笔记(篇二)
2008/10/26 Javascript
extjs 学习笔记 四 带分页的grid
2009/10/20 Javascript
jQuery 动态酷效果实现总结
2009/12/27 Javascript
jQuery新闻滚动插件 jquery.roller.js
2011/06/27 Javascript
JS获取并操作iframe中元素的方法
2013/03/21 Javascript
什么是cookie?js手动创建和存储cookie
2014/05/27 Javascript
JS实现图片无间断滚动代码汇总
2014/07/30 Javascript
node.js中的fs.fsyncSync方法使用说明
2014/12/15 Javascript
js闭包实现按秒计数
2015/04/23 Javascript
Vue.js 父子组件通讯开发实例
2016/09/06 Javascript
jQuery插件HighCharts实现的2D条状图效果示例【附demo源码下载】
2017/03/15 Javascript
JS实现颜色的10进制转化成rgba格式的方法
2017/09/04 Javascript
浅谈Vue SSR 的 Cookies 问题
2017/11/20 Javascript
JavaScript实现选项卡效果的分析及步骤
2019/04/16 Javascript
一个基于flask的web应用诞生 用户注册功能开发(5)
2017/04/11 Python
Python中super函数的用法
2017/11/17 Python
Pycharm 字体大小调整设置的方法实现
2019/09/27 Python
Python集合操作方法详解
2020/02/09 Python
Python unittest单元测试框架及断言方法
2020/04/15 Python
pytorch实现查看当前学习率
2020/06/24 Python
CSS3 media queries + jQuery实现响应式导航
2016/09/30 HTML / CSS
CSS3实现可翻转的hover效果
2018/05/23 HTML / CSS
使用CSS3实现input多选框自定义样式的方法示例
2019/07/19 HTML / CSS
Giglio美国站:意大利奢侈品购物网
2018/02/10 全球购物
市场营销专业推荐信
2013/11/03 职场文书
创业计划书的内容步骤和要领
2014/01/04 职场文书
经理管理专业毕业自荐书范文
2014/02/12 职场文书
五水共治一句话承诺
2014/05/30 职场文书
安全月宣传标语
2014/10/07 职场文书
2016年情人节广告语
2016/01/28 职场文书
纯CSS如何禁止用户复制网页的内容
2021/11/01 HTML / CSS