Skip to content

Instantly share code, notes, and snippets.

@chan-ume
Last active Jun 12, 2021
Embed
What would you like to do?
import cv2
import requests
import json
import numpy as np
from datetime import datetime
import time
TOKEN = "XXXXXXXXXXXXX"
CHANNEL = "XXXXXXXXXXXXXX"
URL = "https://slack.com/api/files.upload"
base_file_name = "/home/XXXXXX/images/{}.png"
# 不審物判定の閾値 移動物体のピクセル数がこの値を超えたら異常
MIN_MOMENT = 10000
# slackへファイルを送信
def send_slack(file_name):
files = {'file': open(file_name, 'rb')}
param = {
'token':TOKEN,
'channels':[CHANNEL],
'initial_comment': "initial_comment",
}
r = requests.post(url=URL, data=param, files=files)
print(r.json())
# フレーム差分の計算
def frame_sub(img1, img2, img3, th):
diff1 = cv2.absdiff(img1, img2)
diff2 = cv2.absdiff(img2, img3)
diff = cv2.bitwise_and(diff1, diff2)
diff[diff < th] = 0
diff[diff >= th] = 255
mask = cv2.medianBlur(diff, 5)
return diff
def main():
# カメラのキャプチャ
cap = cv2.VideoCapture(0)
# フレームを3枚取得してグレースケール変換
frame1 = cv2.cvtColor(cap.read()[1], cv2.COLOR_RGB2GRAY)
frame2 = cv2.cvtColor(cap.read()[1], cv2.COLOR_RGB2GRAY)
frame3_color = cap.read()[1]
frame3 = cv2.cvtColor(frame3_color, cv2.COLOR_RGB2GRAY)
while(cap.isOpened()):
# フレーム間差分を計算
mask = frame_sub(frame1, frame2, frame3, th=10)
# 白色領域のピクセル数を算出
moment = cv2.countNonZero(mask)
# 白色領域のピクセル数が一定以上なら不審物有りと判定
if moment > MIN_MOMENT:
dt_now = datetime.now()
print("異常状態:", dt_now)
file_name = base_file_name.format(dt_now.strftime('%Y%m%d%H%M%S'))
cv2.imwrite(file_name, frame3_color)
send_slack(file_name)
# 3枚のフレームを更新
frame1 = frame2
frame2 = frame3
frame3_color = cap.read()[1]
frame3 = cv2.cvtColor(frame3_color, cv2.COLOR_RGB2GRAY)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print("---")
time.sleep(3)
cap.release()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment