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

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

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

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

(0)

相关推荐

  • 树莓派+摄像头实现对移动物体的检测

    在上一篇文章中实现了树莓派下对摄像头的调用,有兴趣的可以看一下:python+opencv实现摄像头调用的方法 接下来,我们将使用python+opencv实现对移动物体的检测 一.环境变量的配置 我们可以参照上一篇文章对我们的树莓派进行环境的配置 当我们将cv2的库安装之后,就可以实现对摄像头的操作 二.摄像头的连接 在此实验中,我使用的为usb摄像头 当我们连接摄像头之后,终端输入 ls /dev/video* 如果终端提示如下: 则表示摄像头连接成功 三.编码实现对移动物体的检测 使用py

  • 树莓派实现移动拍照

    驱动树莓派gpio的中间层库函数有wiringPi,BCM2835,以及PRi.GPIO,这里我选择使用Python语言开发的PRi.GPIO. 1.安装RPi.GPIO (1)先安装python-dev,输入以下指令. sudo apt-get install python-dev (2)安装RPi.GPIO wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar.gz #解压: tar -zxvf

  • Python+树莓派+YOLO打造一款人工智能照相机

    不久之前,亚马逊刚刚推出了DeepLens.这是一款专门面向开发人员的全球首个支持深度学习的摄像机,它所使用的机器学习算法不仅可以检测物体活动和面部表情,而且还可以检测类似弹吉他等复杂的活动.虽然DeepLens还未正式上市,但智能摄像机的概念已经诞生了. 今天,我们将自己动手打造出一款基于深度学习的照相机,当小鸟出现在摄像头画面中时,它将能检测到小鸟并自动进行拍照.最终成品所拍摄的画面如下所示: 相机不傻,它可以很机智 我们不打算将一个深度学习模块整合到相机中,相反,我们准备将树莓派"挂钩&q

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

    本文实例为大家分享了树莓派动作捕捉抓拍存储图像的具体代码,供大家参考,具体内容如下 #!/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 "su

  • 又拍云存储同步脚本

    本blog使用的服务器是AWS EC2,选用节点位于日本,所以访问速度只能说凑合.前段时间把网站上的css.js以及图片等静态资源放在又拍云存储上,访问速度明显提高不少.由于网站没有备案,所以不能使用自己的域名来直接访问又拍云存储上的内容,只能通过又拍云存储的三级域名来访问. 实现大致步骤如下: 1.注册并激活又拍云账号: 2.登入后在"操作员管理"中添加一个账号,账号在ftp中会使用到: 3."空间管理"中创建一个空间,注意最好是选择"文件类空间&quo

  • python图像常规操作

    使用python进行基本的图像操作与处理 前言: 与早期计算机视觉领域多数程序都是由 C/C++ 写就的情形不同.随着计算机硬件速度越来越快,研究者在考虑选择实现算法语言的时候会更多地考虑编写代码的效率和易用性,而不是像早年那样把算法的执行效率放在首位.这直接导致近年来越来越多的研究者选择 Python 来实现算法. 今天在计算机视觉领域,越来越多的研究者使用 Python 开展研究,所以有必要去学习一下十分易用的python在图像处理领域的使用,这篇博客将会介绍如何使用Python的几个著名的

  • Linux下的信号详解及捕捉信号

    信号的基本概念 每个信号都有一个编号和一个宏定义名称 ,这些宏定义可以在 signal.h 中找到. 使用kill -l命令查看系统中定义的信号列表: 1-31是普通信号: 34-64是实时信号 所有的信号都由操作系统来发! 对信号的三种处理方式 1.忽略此信号:大多数信号都可使用这种方式进行处理,但有两种信号却决不能被忽略.它们是:SIGKILL和SIGSTOP.这两种信号不能被忽略的,原因是:它们向超级用户提供一种使进程终止或停止的可靠方法.另外,如果忽略某些由硬件异常产生的信号(例如非法存

  • PHP图片裁剪函数(保持图像不变形)

    为了完成图片上传之后自动的裁剪,然后在前台显示出裁剪出的图片.需求如上,源码如下: 复制代码 代码如下: <? *exif_imagetype -- 判断一个图像的类型 *说明:函数功能是把一个图像裁剪为任意大小的图像,图像不变形 * 参数说明:输入 需要处理图片的 文件名,生成新图片的保存文件名,生成新图片的宽,生成新图片的高 */ // 获得任意大小图像,不足地方拉伸,不产生变形,不留下空白         function my_image_resize($src_file, $dst_f

  • JSP中的编译指令和动作指令的两点区别

    JSP中的编译指令和动作指令的区别 1.编译指令是通知Servlet引擎的处理消息,而动作指令只是运行时的脚本动作 2.编译指令是在将JSP编译成Servlet时起作用,而动作指令可替换成JSP脚本,是JSP脚本标准化写法

  • 简介Lua脚本与Redis数据库的结合使用

    可能你已经听说过Redis 中嵌入了脚本语言,但是你还没有亲自去尝试吧?  这个入门教程会让你学会在你的Redis 服务器上使用强大的lua语言. Hello, Lua! 我们的第一个Redis Lua 脚本仅仅返回一个字符串,而不会去与redis 以任何有意义的方式交互. 复制代码 代码如下: local msg = "Hello, world!" return msg 这是非常简单的,第一行代码定义了一个本地变量msg存储我们的信息, 第二行代码表示 从redis 服务端返回msg

  • python使用wxpy实现微信消息防撤回脚本

    本文实例为大家分享了python实现微信消息防撤回的具体代码,供大家参考,具体内容如下 使用了sqlite3保存数据,当有人撤回消息时取出数据发送到文件传输助手. 文件的话会先保存到本地,语音会以文件的方式发送. wxpy 和 itchat很久没更新了,有些功能没法用了,web微信也不知道什么时候会凉. 帮助信息在注释里. # -*- coding: utf-8 -*- # 使用sqlite3保存message,当有人撤回消息时在数据库中通过ID检索该消息是否存在,如果存在则将撤回的消息发送到文

  • 浅谈python opencv对图像颜色通道进行加减操作溢出

    由于opencv读入图片数据类型是uint8类型,直接加减会导致数据溢出现象 (1)用Numpy操作 可以先将图片数据类型转换成int类型进行计算, data=np.array(image,dtype='int') 经过处理后(如:遍历,将大于255的置为255,小于0的置为0) 再将图片还原成uint8类型 data=np.array(image,dtype='uint8') 注意: (1)如果直接相加,那么 当像素值 > 255时,结果为对256取模的结果,例如:(240+66) % 256

  • Spring Security将用户数据存储到数据库的方法

    一.UserDetailService Spring Security 支持多种不同的数据源,这些不同的数据源最终都将被封装成 UserDetailsService 的实例,在微人事(https://github.com/lenve/vhr)项目中,我们是自己来创建一个类实现 UserDetailsService 接口,除了自己封装,我们也可以使用系统默认提供的 UserDetailsService 实例,例如上篇文章和大家介绍的 InMemoryUserDetailsManager . 我们来

随机推荐