LoginSignup
3
2

More than 1 year has passed since last update.

Webカメラで猫を検出したときにLINEに画像を送る

Posted at

目的

Webカメラで猫を検出したときにLINEにメッセージとして画像を送るようにすること

前提条件

このシステムを構築したときの条件について

システム構成

開発用PC
Line ⇐ RaspberryPi4 ⇐ Web Camera

環境

開発用PC

Ubuntu18.04
Python3

Raspberry Pi4 ModelB

microSD 128GB
Ubuntu18.04
Python3

コーディング

必要なライブラリをインポートする

import cv2
import requests
import os

Lineに送るための初期設定をする

def init():
    url = "https://notify-api.line.me/api/notify"
    access_token = 'トークン' #取得したトークンを入力
    headers = {'Authorization': 'Bearer ' + access_token}

Webカメラの設定をする
・画像を取得する
・取得した画像の中に猫がいるかを判断する
・猫がいた場合は、画像をラインに送信する

def capture()
    cap = cv2.VideoCapture(0)
    i = 0
    while 1:
        flag1 = 0
        ret, frame = cap.read()
        path = 'img' + str(i) + '.jpg'
        cv2.imwrite(path, frame)
        result, flag2 = detect(flag1, path, 'haarcascade_frontalcatface.xml')
        cv2.imwrite(path, result)
        if flag2 == 1:
            files = {'imageFile': open(path, 'rb')}
            r = requests.post(url, headers = headers, files = files,)
        os.remove(path)
        key = cv2.waitKey(10000)
        i = i + 1

猫が画像の中にいるのかを判断する

def detect(flag, imagefilename, cascadefilename):
    srcimg = cv2.imread(imagefilename)
    if srcimg is None:
        print('cannot load image')
        sys.exit(-1)
    dstimg = srcimg.copy()
    cascade = cv2.CascadeClassifier(cascadefilename)
    if cascade.empty():
        print('cannnot load cascade file')
        sys.exit(-1)
    objects = cascade.detectMultiScale(srcimg, 1.1, 3)
    for (x, y, w, h) in objects:
        print(x, y, w, h)
        flag = 1
        cv2.rectangle(dstimg, (x, y), (x + w, y + h), (0, 0, 255), 2)
    return dstimg, flag

Gitにファイルをアップロードしておきますので必要でしたらご利用ください。

git clone https://github.com/applepie319/CMS.git

参考

3
2
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
3
2