分享一个能自动网络上传的树莓派监控相机

现在智能摄像头已经很普遍了,可是技术宅不就应该做个别人需要花钱买的高科技玩意吗?分享一个能自动网络上传的监控相机,基于树莓派设计,功能也不低,哈哈!
这个监控相机由一个简单的 Python程序控制的:

none.gif

实现功能:

启动相机,捕捉静止图像
检查连接到互联网
自动上传图片到WebAPI
如果连接失败,图像被缓存到本地文件系统
保存的图像将在下一次程序启动上传
详细的制作教程见附件吧,已经整理好成图文了!
本教程要求你有对以下常识的了解:

树莓派
能把树莓派从一块板砖变成一个可操作的电脑
能用USB无线适配器把树莓派连接到网络
修改树莓派的设置,让相机能用
熟悉Python,IDLE 环境,运行Python程序
下载并安装Python模块

代码:
  1. import requests
  2. import picamera
  3. import os
  4. import os.path
  5. import time
  6. from datetime import datetime
  7.  
  8. # ----------------------- globals variables-----------------------
  9.  
  10. # ----Image Extension is JPG by default ----
  11. gImgExt="jpg"
  12.  
  13. # ---- Number of images to be displayed at one time on the web gallery ----
  14. gImgCount=6
  15.  
  16. # ---- Program Development/Production Mode ----
  17. # To run program in debug mode, set  gDebugMode =1
  18. # Make sure to have a file named sample_image.jpg in the same folder as the Watcher.py program
  19. # Once testing is complete, set this flag to 0
  20. gDebugMode=1
  21.  
  22. # ---- Program Execution Mode ----
  23. # Instead of using the cron scheduler, you can run this program in an endless loop
  24. # Set gRunMode to a value other than "single" to enable the endless loop
  25. # Pros: You can skip the entire Crontab scheduling part
  26. # Cons: You have to start the Watcher.py program manually each time you restart your Pi or make changes to it
  27. # CAUTION: To run using Cron, set the gRunMode back to "single"
  28. gRunMode="single"
  29.  
  30. # ---- Marker File ----
  31. # This file will be created in the same folder as Watcher.py
  32. # If connection to the internet fails, the name of the last image captured by the
  33. # camera will be written to this file. No more images will be captured until the
  34. # image is successfully uploaded the next time internet connectivity is restored
  35. gLogFile="0.txt"
  36.  
  37. # ---- Web API Service ----
  38. # When gDebugMode is set to 1, the program looks for an API service on your local machine
  39. # The gAccessKey key can be anything you want it to be, but the API service must also have an identical key!
  40. # When Web APIs uplod method will not accept upload if no access key is provided with the image file
  41.  
  42. gUrl="http://your_web_service.com/"
  43. gBizUrl="http://your_web_service.com/api/upload"
  44. gAccessKey ="a-very-long-and-gibberish-key-must-be-set-here"
  45.  
  46.  
  47. if(gDebugMode==1):
  48.     gUrl="http://your_local_computer_name:port_number/Home/"
  49.     gBizUrl="http://your_local_computer_name:port_number/api/upload/"
  50.    
  51.  
  52. # ---- function to test internet connection ----
  53. # note! this is a function to check for net connectivity
  54. # and not for a valid domain. This function will still return
  55. # success if an invalid url is specified.
  56.  
  57. def checkConnection():
  58.     try:
  59.         resp = requests.get(gUrl)
  60.         return resp.status_code        
  61.     except:
  62.          return -1
  63.  
  64.  
  65. # ---- function to upload the file to the remote server ----
  66. # ---- The accessKey set above will need to be added to the upload request --
  67. def UploadFile(imgFileNm,url):
  68.     f = open (imgFileNm,'rb')
  69.     textData = {'caption': imgFileNm, 'accessKey': gAccessKey, 'imgCount':gImgCount}
  70.     resp = requests.post(url = url, files =  {'file':f}, data = textData)
  71.     if(gDebugMode==1):
  72.         print resp.text
  73.     return resp.status_code
  74.  
  75. # ---- function to write to a local log file  ----
  76. def WriteToLog(imageFileNm,logFileNm,erase):
  77.     lf=open(logFileNm,'w')
  78.     if(erase):
  79.         lf.truncate()
  80.     lf.write(imageFileNm)
  81.     lf.close()
  82.  
  83. # ---- function to read from a local log file  ----
  84. # ---- limitation: file contains one line with just the image name --
  85. def ReadLog(logFileNm):
  86.     lf=open(logFileNm)
  87.     fn=lf.read()
  88.     lf.close()
  89.     return fn
  90.  
  91.  
  92. # ---- function to read from a local log file  ----
  93. def DeleteFile(fileNm):
  94.     if(os.path.isfile(fileNm)):
  95.         os.remove(fileNm)
  96.  
  97. # ---- function to build image file name  ----
  98. # ---- name of the file will be in the current date-time stamp
  99. # ---- the remote API service contains logic to use the file name to identify
  100. # ---- the time the image was captured by the camera and display it as a caption
  101. # ---- under the corresponding image in the web gallery
  102.  
  103. def BuildFileNm(fileExt):
  104.     today = datetime.now()
  105.     fileNm=str(today.month)+"_"+str(today.day)+"_"+str(today.year)+ "__" + \
  106.             str(today.hour)+"_"+str(today.minute)+"_"+str(today.second)+"_"+str(today.microsecond)
  107.     return "{0}.{1}".format(fileNm,fileExt)
  108.  
  109. # ---- function to check for a fle --
  110. def FileExists(fileNm):
  111.     if(os.path.isfile(fileNm)):
  112.         return 1
  113.     else:
  114.         return 0
  115.  
  116.  
  117. # -- the main function --
  118. def main():
  119.    
  120.     #   activate the camera
  121.     camera = picamera.PiCamera()
  122.     #   forever loop - this loop will break after the first run if program is set to "single" mode as described above
  123.     while(1==1):
  124.         imgFileNm=""
  125.         if(FileExists(gLogFile)==0):
  126.             #   last upload succeeded | generate new image file name | capture new image with the pi camera
  127.             imgFileNm=BuildFileNm(gImgExt)
  128.             #   to avoid triggering the camera during testing, simply upload an image from the local folder
  129.             if(gDebugMode==1):
  130.                 imgFileNm="sample_image.jpg"
  131.             else:
  132.                 print("picam will capture an image named {0}".format(imgFileNm))
  133.                 camera.capture(imgFileNm)
  134.         else:
  135.             #   last upload failed | read image name from file | a file with this name should exist when it was captured last time
  136.             imgFileNm=ReadLog(gLogFile)
  137.             if(gDebugMode==1):
  138.                 print("name of image captured last time is {0}".format(imgFileNm))
  139.  
  140.  
  141.         #   check internet connection before attempting upload
  142.         if (checkConnection() == 200):
  143.             print("Success! Connected to Internet, proceeding to upload...")
  144.             #   upload image to web api
  145.             r = UploadFile(imgFileNm,gBizUrl)
  146.             if(r==200):
  147.                 #   upload successful - delete marker file but retain image if debugging for testing next time
  148.                 print("Upload Success! purging local image...")
  149.                 DeleteFile(gLogFile)
  150.                 if(gDebugMode==0):
  151.                     DeleteFile(imgFileNm)
  152.             else:
  153.                 #  upload failed - cache current image to marker file
  154.                 WriteToLog(imgFileNm,gLogFile,1)
  155.         else:
  156.             print("Fail! No connection, service unavailable or incorrect service URL")
  157.             #   cache image to log | don't capture image until the last image has been uploaded successfully
  158.             WriteToLog(imgFileNm,gLogFile,1)
  159.             print("Local image saved to log file...will be uploaded next time internet or service is available")
  160.  
  161.         #   Exit program if execution is set to single mode
  162.         if(gRunMode=="single"):
  163.             break
  164.  
  165.     #   release camera resources before exit
  166.     camera.close()
  167.                                 
  168.    
  169.  
  170. # -- execute main function --
  171. main()
  172.  
复制代码

 

文件到原文下载,原文出自:https://bbs.usoftchina.com/thread-209288-1-1.html

谷歌翻译: 如果相机拍照而没有人注意到,它真的发生了吗?在本书中,我们将向您展示如何制作基于Raspberry Pi的相机系统,以便您可以捕获延时图像并通过WiFi查看,如果检测到运动则触发相机,甚至可以执行基本面部认可作为机器学习方法的介绍。 拿一个Raspberry Pi并添加一个相机模块,你就有了一个可编程相机。添加一些软件,您就可以开始进行有趣的监视和自动对象识别工作。将Pi激活为WiFi节点,您可以远距离完成所有这些美妙的事物。 一个好的监控系统不仅仅是拍照。它还应该将这些图片转化为可操作的信息,从而增加您的知识。现在可以在软件中轻松完成,我们将向您展示如何操作。 本书汇集了一系列小技巧 - 设置Pi相机,将Pi广播作为WiFi设备,增加时间流逝和运动检测和人脸识别,并在其上粘贴电池组,以便它可以在任何地方运行 - 创建便携式间谍相机。我们在“Find the Pi”派对比赛,在我们的实验室中实施隐私尊重的安全性,以及炫耀面部识别等现代技术的过程中使用了这些装备。其他用途可能包括监控鹿和野生动物,检查您的邮箱到达邮件,以及捕获自然事件或交通模式的延时序列。 我们的第一个项目是创建一个便携式“SpyPi”摄像机设备,通过WiFi广播图像而无需网络 - 您只需登录它即可查看摄像机看到的内容。它非常适合“寻找相机”狩猎挑战或独立安全。 第二个项目将涉及设置一个延时摄像头,可以进行简单的运动检测 - 非常适合监控位置。该系统将包括一周后自动删除旧图像。 第三个项目是为您的SpyPi添加面部检测和面部识别功能。在此过程中,您将了解这些项目结束时安装的工具和软件,以便您可以超越本书并探索其他机器学习方法。 所以抓住一个Pi,一个SD卡,一个USB摄像头一个USB电池组,让我们走吧!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值