Camera_Discord.py
from discord import Webhook
import discord
import aiohttp
import asyncio
import cv2
import time
import datetime
import cv2 as cv
webhook_url = "Discdord Webhook URL"
#カメラで撮影用
camera = cv2.VideoCapture(0) #タイトルの管理
id=0
#動体検知用
save_dir = './image/'
fn_suffix = 'motion_detect.jpg'
cap = cv.VideoCapture(0)
cap.set(cv.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, 480)
DELTA_MAX = 255
DOT_TH = 20
MOTHON_FACTOR_TH = 0.20
avg = None
while True:
ret,frame =camera.read()
motion_detected = False
if not ret:
break
dt_now = datetime.datetime.now() #データを取得した時刻
#ファイル名と、画像中に埋め込む日付時刻
dt_format_string = dt_now.strftime('%Y-%m-%d %H:%M:%S')
f_name = dt_now.strftime('%Y%m%d%H%M%S%f') + "_" + fn_suffix
# モノクロにする
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
#比較用のフレームを取得する
if avg is None:
avg = gray.copy().astype("float")
continue
# 現在のフレームと移動平均との差を計算
cv.accumulateWeighted(gray, avg, 0.6)
frameDelta = cv.absdiff(gray, cv.convertScaleAbs(avg))
# デルタ画像を閾値処理を行う
thresh = cv.threshold(frameDelta, DOT_TH, DELTA_MAX, cv.THRESH_BINARY)[1]
#モーションファクターを計算する。全体としてどれくらいの割合が変化したか。
motion_factor = thresh.sum() * 1.0 / thresh.size / DELTA_MAX
motion_factor_str = '{:.08f}'.format(motion_factor)
#モーションファクターがしきい値を超えていれば動きを検知したことにする
if motion_factor > MOTHON_FACTOR_TH:
motion_detected = True
# 動き検出していれば画像を保存する
if motion_detected == True:
title="image"+str(id)+".jpeg"
cv2.imwrite(title, frame)
print(title)
dt_now = datetime.datetime.now()
#メッセージの詳細
username = "test"
title = (dt_now.strftime('%Y年%m月%d日 %H:%M:%S'))
description = "description"
color_hex = "ff0000"
image_path = "image"+str(id)+".jpeg"
pathid = "image"+str(id)+".jpeg"
#discordに画像を送信する
file = discord.File(image_path, filename="image"+str(id)+".jpeg")
embed = discord.Embed(
title=title, description=description, color=int(color_hex, 16)
).set_image(url="attachment://"+pathid)
async def foo():
async with aiohttp.ClientSession() as session:
webhookdata = Webhook.from_url(webhook_url, session=session)
await webhookdata.send(username=username, embed=embed, file=file)
asyncio.run(foo())
#タイトルの変更
id +=1
#一秒ごとに実行し直す
time.sleep(1)
key = cv2.waitKey(1)
if key == 27:
break
camera.release()
cv2.destroyAllWindows()
この記事が気に入ったらサポートをしてみませんか?