LoginSignup
17
41

More than 1 year has passed since last update.

OpencvとPythonで監視カメラ(SecurityCamera)を作る方法

Last updated at Posted at 2020-10-03

0.最初に

今回作るものがどういう感じで動くのか見てみたい方は、こちら(youtubeの動画)でどうぞ。

1.処理を書く

security_cam.py
import cv2
from datetime import datetime
import requests
import time

token = 'Your Token'

cap = cv2.VideoCapture(0)
lastframe = None

def send_msg():
    url = 'https://notify-api.line.me/api/notify'
    headers = {'Authorization':'Bearer '+token}
    data = {"message":"Someone in your room."}
    image = '/home/igor-bond/image.jpg'
    file = {'imageFile': open(image, 'rb')}
    r = requests.post(url, headers=headers, params=data, files=file,)

while cap.isOpened():
    ret,frame = cap.read()
    if ret == True:
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)

        if lastframe is None:
            lastframe = gray.astype("float")

        cv2.accumulateWeighted(gray,lastframe,0.6)
        frame_diff = cv2.absdiff(gray,cv2.convertScaleAbs(lastframe))
        thresh = cv2.threshold(frame_diff,3,255,cv2.THRESH_BINARY)[1]
        contours,hierarchy = cv2.findContours(thresh.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

        for c in contours:
            if cv2.contourArea(c) > 30:
                time.sleep(0.2)
                now = datetime.now()
                img = cv2.resize(frame,(int(frame.shape[1]*0.5),int(frame.shape[0]*0.5)))
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(img,f'{now}',(100,350),font,1,(0,0,255),4,cv2.LINE_AA)
                cv2.imwrite('/home/igor-bond/image.jpg',img)
                send_msg()
                lastframe = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY).astype("float")
                break

        cv2.imshow('frame',frame)  

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

cv2.destroyAllWindows()
cap.release()

最初の関数はラインに画像を送るやつで以前も紹介したことがあるのでここでは割愛します。ここ(youtubeの動画)でも紹介しています。そして今回はフレーム間の違いを求めてそこで画素値が3以上のものはそれを255にしてそこで輪郭を求めてある一定の面積をこえた輪郭があれば動いたとみなす。これはとても小さな変化も検出してしまうのでそれを防ぐためです。そして、監視カメラっぽくなるように右下に時刻を付け加えて画像として保存します。画像の名前を変えていないのは変えると画像がたくさんたまってしまい、今回は保存したあとすぐにラインに送る関数を発動して送信しているのでこうしても問題がないためです。最後にその時のフレームを一番最後のものとしてこれを繰り返します。

最後に

この監視カメラの作り方はYoutubeでも解説しているのでぜひそちらもご覧ください。質問やアドバイスなどがあればぜひコメントしてください。

17
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
41