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


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 相关文章推荐
仅用50行代码实现一个Python编写的计算器的教程
Apr 17 Python
详解Python中dict与set的使用
Aug 10 Python
日常整理python执行系统命令的常见方法(全)
Oct 22 Python
浅谈python中的数字类型与处理工具
Aug 02 Python
Python常用字符串替换函数strip、replace及sub用法示例
May 21 Python
Python读取excel中的图片完美解决方法
Jul 27 Python
python实现K近邻回归,采用等权重和不等权重的方法
Jan 23 Python
Python实现对特定列表进行从小到大排序操作示例
Feb 11 Python
PyTorch基本数据类型(一)
May 22 Python
Pytorch在dataloader类中设置shuffle的随机数种子方式
Jan 14 Python
在keras中实现查看其训练loss值
Jun 16 Python
Python线程池与GIL全局锁实现抽奖小案例
Apr 13 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
Yii框架中memcache用法实例
2014/12/03 PHP
基于jquery和svg实现超炫酷的动画特效
2014/12/09 Javascript
jQuery中:visible选择器用法实例
2014/12/30 Javascript
jquery解决客户端跨域访问问题
2015/01/06 Javascript
JavaScript检测浏览器cookie是否已经启动的方法
2015/02/27 Javascript
JavaScript中的函数嵌套使用
2015/06/04 Javascript
详解JavaScript中shift()方法的使用
2015/06/09 Javascript
简单谈谈Javascript中类型的判断
2015/10/19 Javascript
Jquery获取当前城市的天气信息
2016/08/05 Javascript
详解JSON1:使用TSQL查询数据和更新JSON数据
2016/11/21 Javascript
javascript DOM的详解及实例代码
2017/03/06 Javascript
将jquery.qqFace.js表情转换成微信的字符码
2017/12/01 jQuery
AngularJS对动态增加的DOM实现ng-keyup事件示例
2018/03/12 Javascript
详解项目升级到vue-cli3的正确姿势
2019/01/28 Javascript
了解Javascript中函数作为对象的魅力
2019/06/19 Javascript
JavaScript实现缓动动画
2020/11/25 Javascript
[01:02:25]2014 DOTA2华西杯精英邀请赛 5 24 iG VS DK
2014/05/26 DOTA
[55:03]LGD vs EG 2018国际邀请赛小组赛BO2 第二场 8.17
2018/08/18 DOTA
python将图片文件转换成base64编码的方法
2015/03/14 Python
详解Python中的array数组模块相关使用
2016/07/05 Python
Python虚拟环境项目实例
2017/11/20 Python
解决Python3中的中文字符编码的问题
2018/07/18 Python
对python生成业务报表的实例详解
2019/02/03 Python
用scikit-learn和pandas学习线性回归的方法
2019/06/21 Python
python+tifffile之tiff文件读写方式
2020/01/13 Python
python发qq消息轰炸虐狗好友思路详解(完整代码)
2020/02/15 Python
如何解决flask修改静态资源后缓存文件不能及时更改问题
2020/08/02 Python
美国围栏公司:Walpole Outdoors
2019/11/19 全球购物
2014年元旦联欢会活动策划方案
2014/02/16 职场文书
学校政风行风整改方案
2014/10/25 职场文书
2014年高中教师工作总结
2014/12/19 职场文书
财务部岗位职责
2015/02/03 职场文书
企业财务总监岗位职责
2015/04/03 职场文书
单位考核鉴定意见
2015/06/05 职场文书
Redis性能监控的实现
2021/07/09 Redis
Java结构型设计模式之组合模式详解
2022/09/23 Java/Android