树莓派Ubuntu mate中借助OpenCV实现摄像头定时拍照并保存python语言

时间:2022-03-22 10:25:05
刚刚入门的小白,第一次写博客,有不妥的地方还望各路大佬多多指教~

本帖主要是介绍利用python语言如何在树莓派Ubuntu mate中借助OpenCV实现摄像头给定间隔时间连续拍照,并以拍照时间命名保存照片。这里用的摄像头是树莓派自带摄像头,USB外接摄像头可能不太适用!

首先,在树莓派Ubuntu mate中安装与配置摄像头(enabled),

正确安装摄像头~~

安装
 1. sudo apt update
 2. sudo apt upgrade
 3. sudo apt-get install raspi-config
配置命令
sudo raspi-config
依次选择3 Interfacing options/P1 camera, 最后选择OK完成enable,完成以上需要重启电脑!
重启电脑
sudo reboot

其次,安装OpenCV,这一步操作比较繁琐,消耗时间也较长(大约需要几小时吧),可以参考下面链接(这位大神讲的很清楚):https://blog.csdn.net/layallan/article/details/78328943(树莓派3b 基于python3.4安装OpenCV3)

接下来就是本文的重点了,实现摄像头给定间隔时间连续拍照的python程序
该程序主要有以下几点功能:
1.给定间隔时间连续抓拍(我设的30S拍一次)
time.sleep(30)

2.利用OpenCV实现图像格式等转换
3.以拍摄时间命名保存图片,便于图片处理
 for filename in camera.capture_continuous('img{timestamp:%Y-%m-%d-%H-%M-%S}.jpeg'):
          print('Captured %s' % filename)

话不多说,上程序:
import picamera
import picamera.array
import time
import numpy as np
import cv2
import io
import datetime
from time import sleep
from datetime import datetime, timedelta

def PreviewOpencvJpeg(camera):
    with io.BytesIO() as stream:
        for frame in camera.capture_continuous(stream, format='jpeg', splitter_port = 2, resize = (640,480), use_video_port=True):
            data = np.fromstring(frame.getvalue(),dtype=np.uint8)
            d1 = datetime.datetime.now()
            cv_image = cv2.imdecode(data, 1)
            d = datetime.datetime.now() - d1
            print ("consuming %dms" % (d.microseconds/1000))
            print (cv_image.shape)
            cv2.imwrite("{timestamp:%Y-%m-%d-%H-%M-%S}.png",cv_image)
            stream.seek(0)
            stream.truncate(0)       

with picamera.PiCamera() as camera:
    camera.start_preview()
    camera.resolution = (1920,1080)
    camera.framerate = 25 
    camera.annotate_text = "HKUTANGYU.Inc"
    camera.vflip = True
    camera.hflip = True
    time.sleep(5)
    for filename in camera.capture_continuous('img{timestamp:%Y-%m-%d-%H-%M-%S}.jpeg'):
          print('Captured %s' % filename)
          time.sleep(30)
    print ("start preview direct from GPU")
    camera.start_preview() # the start_preview() function
    PreviewOpencvJpeg(camera)
如果有更高效的方法,欢迎各路大佬交流~