A simple system that automatically shoots with object detection and sends it to LINE

Introduction

Shoots automatically when an object crosses! Introducing a system that sends images to LINE.

** Is your cat eating properly during a one-night, two-day excursion? I was worried if I was drinking water, so I made it. ** **

It will be a simple system using Raspberry Pi, It is recommended because you can check the camera image on LINE while you are out, such as those who have pets.

reference

Book "Gently Start Raspberry Pi" It's a very easy-to-understand book for beginners of Raspberry Pi, and I highly recommend it. About 80% of this system borrowed ideas from this book m (_ _) m

System description

This is the GitHub repository. https://github.com/akiraseto/security_cam

Rough flow

  1. Start the Python program and stand by
  2. Automatic detection when a cat passes near the sensor
  3. When you receive the signal, get and save the image with a webcam connected via USB
  4. Notify the latest saved image through LINE notify
  5. You can see images on LINE even when you are out!

Raspberry pi

Raspberry Pi (hereinafter referred to as Raspberry Pi) is used to connect the sensor and the camera.

Connect motion sensor with GPIO Detects when objects that are hotter than the surroundings, such as people and animals, move using infrared rays. I used the unmarked parts of the set for the motion sensor, but there is no problem in using it with the "SE-10" sold in Akizuki. I think. Connect the sensor OUTPUT to GPIO: No. 23 of Raspberry Pi Raspberry Pi GPIO: Connect LED anode to number 18

USB connection with webcam Just stick it in the USB terminal like a PC, and you don't need to do anything special.

Like this ↓ ↓ photo.jpeg

LINEnotify With the API provided by LINE, you can freely send various notifications to LINE by incorporating it into the program. It's quite convenient and seems to have various uses. https://notify-bot.line.me/ja/

This page is detailed. https://qiita.com/iitenkida7/items/576a8226ba6584864d95

Register and cooperate to issue an access token. The access token is displayed only once, so be careful not to forget to copy it.

overall structure

security_cam/
├── README.md
├── config.py #LINE Notify token
└── security_cam.py

#Image storage directory
/media/pi/rasUSB/security_cam/img

As for the images, I don't want to overwhelm the capacity of the boot disk, so I save them separately on a USB memory. Exaggeratedly saying the whole structure, the actual program file is only security_cam.py.

Main code

security_cam.py


import RPi.GPIO as GPIO
from time import sleep
import datetime, requests, cv2, os, glob, config

#LINE Notify token
TOKEN = config.TOKEN
API = 'https://notify-api.line.me/api/notify'

#GPIO port settings
SENSOR_PORT = 23
LED_PORT = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(SENSOR_PORT, GPIO.IN)
GPIO.setup(LED_PORT, GPIO.OUT)

#CV2 preparation
camera = cv2.VideoCapture(0)
IMG_SIZE = (600,400)

#Execute a photo shoot command(File name to date and time)
last_post = datetime.datetime(2000, 1, 1) #Initialize properly
def take_photo():
    global last_post
    #Take a photo
    now = datetime.datetime.now()
    fname = "/media/pi/rasUSB/security_cam/img/" + now.strftime('%Y-%m-%d_%H-%M-%S') + ".jpg "

    #Delete old image
    file_list = glob.glob("/media/pi/rasUSB/security_cam/img/*jpg")
    dif_time = datetime.timedelta(days=3)
    for file in file_list:
        file_time = datetime.datetime.fromtimestamp(os.path.getatime(file))
        if (file_time < now  - dif_time):
            print("remove:{0}".format(file))
            os.remove(file)

    #photograph
    _, frame = camera.read()
    img = cv2.resize(frame, IMG_SIZE)
    ret = cv2.imwrite(fname, img)
    if ret:
        print('Captured image: ' + fname)
    else:
        print('Failed to write image.')

    #Notify LINE
    #However, 10 minutes will not be notified--- (*1)
    sec = (now - last_post).seconds
    if sec < 10 * 60: return
    last_post = now
    #Insert notifications into LINE--- (*2)
    post_data = {'message': 'Nyans'}
    headers = {'Authorization': 'Bearer ' + TOKEN}
    files={'imageFile': open(fname,'rb')}
    res = requests.post(API, data=post_data,
        headers=headers,files=files)
    print(res.text)

try:
    sw = 0 #Continuous shooting prevention
    #Get the value of the sensor repeatedly
    while True:
        v = GPIO.input(SENSOR_PORT)
        if v == GPIO.HIGH:
            GPIO.output(LED_PORT, GPIO.HIGH)
            take_photo()
            sw = 1
        else:
            GPIO.output(LED_PORT, GPIO.LOW)
            sw = 0
        sleep(10.0)
except KeyboardInterrupt:
        pass
GPIO.cleanup()

--I am using the ʻopencvlibrary for camera shooting. There are several ways to install opencv on Raspberry Pi, but this is the easiest and quickest to recommend. https://karaage.hatenadiary.jp/entry/2018/10/05/073000 --Saved images are deleted more than 3 days ago. If you want to extend the number of days, change it to an appropriate number of days with L30:dif_time = datetime.timedelta (days = 3)`.

This is a simple program.

in conclusion

To be honest, I use it only occasionally. Not only cats, but every time my family crossed, LINE notifications came bang bang. .. (´Д `) As a recommended usage It's time to leave home for a while, such as a one-night, two-day excursion or going out with your family from morning till night. It feels good to play an active part in checking the state of the cat.

How about those who are worried about eating and drinking water for their pets while they are out? Of course, it's fun to feel relaxed through LINE, such as "Did you come to drink water?" And "You eat too much food."

Recommended Posts

A simple system that automatically shoots with object detection and sends it to LINE
PGM that automatically creates a walking route
Nogizaka46 A program that automatically saves blog images
A Vim plugin that automatically formats Python styles
A simple system that automatically shoots with object detection and sends it to LINE
I made a system that automatically decides whether to run tomorrow with Python and adds it to Google Calendar.
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬
A script that makes it easy to create rich menus with the LINE Messaging API
Steps to create a Job that pulls a Docker image and tests it with Github Actions
A memorandum when I tried to get it automatically with selenium
Try to write a program that abuses the program and sends 100 emails
A light introduction to object detection
Create a program that automatically inputs and sends body temperature every morning [Note]
Create a simple reception system with the Python serverless framework Chalice and Twilio
I want to write an element to a file with numpy and check it.
Load a photo and make a handwritten sketch. With zoom function. Tried to make it.
I tried to make a simple image recognition API with Fast API and Tensorflow
How to send a message to LINE with curl
Save the object to a file with pickle
A Python script that crawls RSS in Azure Status and posts it to Hipchat
I made a Docker Image that reads RSS and automatically tweets regularly and released it.
[Mac] I want to make a simple HTTP server that runs CGI with Python
I made a web application that maps IT event information with Vue and Flask
From installing Flask on CentOS to making it a service with Nginx and uWSGI
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
A beginner tried coloring line art with chainer. I was able to do it.
Collect tweets about "Corona" with python and automatically detect words that became a hot topic due to the influence of "Corona"
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
A script that pings the registered server and sends an email with Gmail a certain number of times when it fails
Try making a simple website with responder and sqlite3
I tried to read and save automatically with VOICEROID2 2
How to convert a class object to a dictionary with SQLAlchemy
Let's make a simple game with Python 3 and iPhone
I made a LINE BOT with Python and Heroku
I tried to automatically generate a password with Python3
I made a tool that makes it a little easier to create and install a public key.
How to start a simple WEB server that can execute cgi of php and python
A learning roadmap that allows you to develop and publish services from scratch with Python
How to interactively draw a machine learning pipeline with scikit-learn and save it in HTML
A story that makes it easy to estimate the living area using Elasticsearch and Python
Recursively get the Excel list in a specific folder with python and write it to Excel.
I made a server with Python socket and ssl and tried to access it from a browser
Let's create a program that automatically registers ID/PW from CSV to Bitwarden with Python + Selenium
A program that failed when trying to create a linebot with reference to "Dialogue system made with python"
Steps to set up Pipenv, create a CRUD app with Flask, and containerize it with Docker
A story that made it possible to automatically create anison playlists from your music files
A simple version of government statistics (immigration control) that is easy to handle with jupyter
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.