Python:通过摄像头抓取图像并自动上传至新浪微博


通过上一篇文章Python:通过摄像头实现的监控功能》见 ,突然想到将每次采集到的图片可以直接上传至微博,然后可以通过手机准实时查看要监控的地方,实现思路如下:

  a.程序A 每30s通过摄像头采集一次图像,并保存;

  b.程序B也是每30s将采集到的图片上传至新浪微博;

  实现如下:

   1. 采集图像程序A:

[python]
  1. #!/usr/bin/env python   
  2. # -*- coding: utf-8 -*-   
  3.   
  4. from VideoCapture import Device  
  5. import time  
  6.   
  7. #最多保存5张抓取到的图片,超过5张,覆盖最早的那一张,依次循环   
  8. MAX_PIC_NUM = 5  
  9.   
  10. #抓取频率,30秒抓取一次   
  11. SLEEP_TIME_LONG = 30  
  12.   
  13. #初始化摄像头   
  14. cam = Device(devnum=0, showVideoWindow=0)  
  15.   
  16. iNum = 0  
  17. while True:  
  18.       
  19.     #抓图   
  20.     cam.saveSnapshot(str(iNum)+ '.jpg', timestamp=3, boldfont=1, quality=75)  
  21.       
  22.     #休眠一下,等待一分钟   
  23.     time.sleep(SLEEP_TIME_LONG)  
  24.       
  25.     #超过5张,则覆盖之前的,否则,硬盘很快就会写满   
  26.     if iNum == MAX_PIC_NUM:  
  27.         iNum = 0  
  28.     else:  
  29.         iNum += 1  
  30.           
2. 上传图片到新浪微博程序B:

[python]
  1. #!/usr/bin/env python   
  2. # -*- coding: utf-8 -*-   
  3.   
  4. from weibopy.auth import OAuthHandler  
  5. from weibopy.api import API  
  6. import ConfigParser  
  7. import time  
  8.   
  9. MAX_PIC_NUM = 5  
  10. SLEEP_TIME_LONG = 30  
  11.   
  12. def press_sina_weibo():  
  13.     ''''' 
  14.     调用新浪微博Open Api实现通过命令行写博文,功能有待完善 
  15.     author: socrates 
  16.     date:2012-02-06 
  17.     新浪微博:@没耳朵的羊 
  18.     '''  
  19.     sina_weibo_config = ConfigParser.ConfigParser()  
  20.     #读取appkey相关配置文件   
  21.     try:  
  22.         sina_weibo_config.readfp(open('sina_weibo_config.ini'))  
  23.     except ConfigParser.Error:  
  24.         print 'read sina_weibo_config.ini failed.'  
  25.       
  26.     #获取需要的信息   
  27.     consumer_key = sina_weibo_config.get("userinfo","CONSUMER_KEY")  
  28.     consumer_secret =sina_weibo_config.get("userinfo","CONSUMER_SECRET")  
  29.     token = sina_weibo_config.get("userinfo","TOKEN")  
  30.     token_sercet = sina_weibo_config.get("userinfo","TOKEN_SECRET")  
  31.   
  32.     #调用新浪微博OpenApi(python版)   
  33.     auth = OAuthHandler(consumer_key, consumer_secret)  
  34.     auth.setToken(token, token_sercet)  
  35.     api = API(auth)  
  36.   
  37.     #通过命令行输入要发布的内容   
  38. #    weibo_content = raw_input('Please input content:')   
  39. #    status = api.update_status(status=weibo_content)   
  40. #    print "Press sina weibo successful, content is: %s" % status.text   
  41.     iNum = 0  
  42.     while True:  
  43.         #上传图片,名称和内容如果重复,open api会检查,内容采用了取当前时间的机制   
  44.         #图片名称从0-5循环遍历   
  45.         status = api.upload(str(iNum)+ '.jpg', time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))  
  46.         time.sleep(SLEEP_TIME_LONG)  
  47.       
  48.         if iNum == MAX_PIC_NUM:  
  49.             iNum = 0  
  50.         else:  
  51.             iNum += 1  
  52.           
  53. if __name__ == '__main__':  
  54.     press_sina_weibo()  

相关内容