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


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 相关文章推荐
python getopt 参数处理小示例
Jun 09 Python
python算法学习之计数排序实例
Dec 18 Python
python实现的简单猜数字游戏
Apr 04 Python
Python计算三角函数之asin()方法的使用
May 15 Python
Python实现模拟时钟代码推荐
Nov 08 Python
python opencv3实现人脸识别(windows)
May 25 Python
pandas 读取各种格式文件的方法
Jun 22 Python
基于wxPython的GUI实现输入对话框(1)
Feb 27 Python
Pycharm新手教程(只需要看这篇就够了)
Jun 18 Python
python-numpy-指数分布实例详解
Dec 07 Python
python检查目录文件权限并修改目录文件权限的操作
Mar 11 Python
Python中flatten( ),matrix.A用法说明
Jul 05 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中的正规表达式(二)
2006/10/09 PHP
wamp下修改mysql访问密码的解决方法
2013/05/07 PHP
php使用ZipArchive函数实现文件的压缩与解压缩
2015/10/27 PHP
PHP 多任务秒级定时器的实现方法
2018/05/13 PHP
PJ Blog修改-禁止复制的代码和方法
2006/10/25 Javascript
经典的解除许多网站无法复制文字的绝招
2006/12/31 Javascript
JavaScript入门教程(3) js面向对象
2009/01/31 Javascript
jquery控制listbox中项的移动并排序的实现代码
2010/09/28 Javascript
JavaScript执行效率与性能提升方案
2012/12/21 Javascript
datagrid框架的删除添加与修改
2013/04/08 Javascript
动态添加option及createElement使用示例
2014/01/26 Javascript
JavaScript定义类和对象的方法
2014/11/26 Javascript
JavaScript中数据结构与算法(五):经典KMP算法
2015/06/19 Javascript
jquery ajax分页插件的简单实现
2016/01/27 Javascript
JS弹出层遮罩,隐藏背景页面滚动条细节优化分析
2016/04/29 Javascript
AngularJS 中的事件详解
2016/07/28 Javascript
关于js二维数组和多维数组的定义声明(详解)
2016/10/02 Javascript
jQuery 选择符详细介绍及整理
2016/12/02 Javascript
jquery实现输入框实时输入触发事件代码
2016/12/21 Javascript
JS使用cookie保存用户登录信息操作示例
2019/05/30 Javascript
关于NodeJS中的循环引用详解
2019/07/23 NodeJs
微信小程序 弹窗输入组件的实现解析
2019/08/12 Javascript
JavaScript进阶(三)闭包原理与用法详解
2020/05/09 Javascript
jQuery实现增删改查
2020/12/22 jQuery
element-ui封装一个Table模板组件的示例
2021/01/04 Javascript
[44:40]2018DOTA2亚洲邀请赛3月30日 小组赛A组Liquid VS OG
2018/03/31 DOTA
简单介绍Python中的readline()方法的使用
2015/05/24 Python
python中管道用法入门实例
2015/06/04 Python
实例讲解Python的函数闭包使用中应注意的问题
2016/06/20 Python
python分析作业提交情况
2017/11/22 Python
python 不同方式读取文件速度不同的实例
2018/11/09 Python
python 实现在一张图中绘制一个小的子图方法
2019/07/07 Python
印度在线购买电子产品网站:Croma
2020/01/02 全球购物
opencv实现图像平移效果
2021/03/24 Python
公司副总经理岗位职责
2015/04/08 职场文书
Nginx实现负载均衡的项目实践
2022/03/18 Servers