Last active
May 17, 2022 01:59
OpenCVとPythonで取得した画像を指定した時刻に動画にしてGoogleドライブにアップロードする
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Copyright (c) 2013 Daniel Bader (http://dbader.org) | |
License: MIT | |
https://github.com/dbader/schedule | |
Copyright(c) 2020 Tatsuro Watanabe | |
""" | |
import cv2 | |
from datetime import datetime | |
import glob | |
import os | |
import shutil | |
from pydrive.auth import GoogleAuth | |
from pydrive.drive import GoogleDrive | |
import schedule | |
def make_video_from_image(path, size, video_file): | |
""" | |
画像ファイルから動画を作成 | |
:param path: 画像ファイルのパス | |
:param size: 画像ファイルのサイズ | |
:param video_file: 動画ファイル(mp4) | |
""" | |
image_path = path + '/*.jpg' | |
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') | |
video = cv2.VideoWriter(video_file, fourcc, 20.0, size) | |
for filename in sorted(glob.glob(image_path)): | |
img = cv2.imread(filename) | |
img = cv2.resize(img, size) | |
video.write(img) | |
video.release() | |
def delete_all_files(path): | |
""" | |
指定したフォルダを削除後、再作成 | |
:param path: 削除するフォルダ | |
""" | |
shutil.rmtree(path) | |
os.mkdir(path) | |
def upload_to_google_drive(video_file): | |
""" | |
googleドライブに動画ファイルをアップロードする | |
:param video_file: アップロードする動画ファイル(mp4) | |
""" | |
gauth = GoogleAuth() | |
gauth.CommandLineAuth() | |
drive = GoogleDrive(gauth) | |
folder_id = os.environ['FOLDER_ID'] # FOLDER_IDは環境変数から取得 | |
f = drive.CreateFile({'title': video_file, | |
'mimeType': 'video/mp4', | |
'parents': [{'kind': 'drive#fileLink', | |
'id': folder_id}]}) | |
f.SetContentFile(video_file) | |
f.Upload() | |
def main(): | |
display_size = (400, 300) # 表示するサイズ | |
cap = cv2.VideoCapture(0) | |
path = 'video_image' # 画像ファイルのパス | |
video_file = 'out.mp4' # 動画ファイル | |
# 毎日9:00に実行 | |
schedule.every().day.at("09:00").do(make_video_from_image, | |
path=path, | |
size=display_size, | |
video_file=video_file) | |
# 毎日9:10に実行 | |
schedule.every().day.at("09:10").do(upload_to_google_drive, | |
video_file=video_file) | |
# 毎日9:20に実行 | |
schedule.every().day.at("09:20").do(delete_all_files, | |
path=path) | |
while True: | |
ok, frame = cap.read() | |
if not ok: | |
continue | |
# 何らかのキーが押されたら終了 | |
if cv2.waitKey(1) != -1: | |
break | |
display_image = cv2.resize(frame, display_size) | |
# 現在時刻を取得 | |
now = datetime.now() | |
now_str = now.strftime('%m%d%H%M%S%f') | |
# 表示する | |
cv2.imshow('window', display_image) | |
# 画像ファイルに書き込む | |
image_file = now_str + ".jpg" | |
f = os.path.join(path, image_file) | |
cv2.imwrite(f, frame) | |
schedule.run_pending() | |
# カメラの終了処理 | |
cap.release() | |
cv2.destroyAllWindows() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment