[PYTHON] Create a web surveillance camera with Raspberry Pi and OpenCV

Create a web surveillance camera with Raspberry Pi and OpenCV

Introduction

`Although it is an article on Mac environment, the procedure is the same for Windows environment. Please read and try the environment-dependent part. ``

Purpose

Display streaming video in your browser.

After reading this article to the end, you will be able to:

No. Overview keyword
1 REST API Flask
2 OpenCV cv2

Complete image

Streaming
IMG_4814.PNG

Execution environment

environment Ver.
macOS Catalina 10.15.6
Raspberry Pi 4 Model B 4GB RAM -
Raspberry Pi OS (Raspbian) 10
Python 3.7.3
Flask 1.1.2
opencv-python 4.4.0.42

Source code

I think that understanding will deepen if you read while actually following the implementation contents and source code. Please use it by all means.

GitHub

Related articles

-From Raspberry Pi setup to Python environment installation -Create a remote control car with Raspberry Pi and Python -Create an LCD (16x2) game with Raspberry Pi and Python

Camera settings

Launch Raspberry Pi Software Configuration Tool

command.sh


~$ sudo raspi-config

Camera enabled

  1. Select 5 Interfacing Options
  2. Select P1 Camera

Reboot

command.sh


~$ sudo reboot

OpenCV dependency

HDF5

HDF5 is a file format and library for storing scientific data.

command.sh


~$ sudo apt-get install -y libhdf5-dev libhdf5-serial-dev libhdf5-103

ATLAS

ATLAS is an approach for the automatic generation and optimization of numerical software.

command.sh


~$ sudo apt-get install -y libatlas-base-dev

JasPer

JasPer is a collection of software (i.e., a library and application programs) for the coding and manipulation of images.

command.sh


~$ sudo apt-get install -y libjasper-dev

Hands-on

download

command.sh


~$ git clone https://github.com/nsuhara/raspi-streaming.git -b master

setup

command.sh


~$ cd raspi-streaming
~$ python -m venv .venv
~$ source .venv/bin/activate
~$ pip install -r requirements.txt
~$ source config

Service start

command.sh


~$ flask run --host=0.0.0.0 --port=5000

access

command.sh


~$ open "http://{host}:5000/raspi-streaming/api?process=front_end&request=app_form&secret_key=M7XvWE9fSFg3"

End of service

command.sh


~$ Control Key + C

App configuration

target.sh


/app
├── __init__.py
├── apis
│   ├── templates
│   │   └── app_form.html
│   └── views
│       ├── __init__.py
│       ├── back_end_handler.py
│       ├── camera.py
│       ├── front_end_handler.py
│       └── main_handler.py
├── common
│   ├── __init__.py
│   └── utility.py
├── config
│   ├── __init__.py
│   ├── localhost.py
│   └── production.py
└── run.py

front-end

target.sh


/app
└── apis
     ├── templates
     │   └── app_form.html
     └── views
         └── front_end_handler.py

front-end control

front_end_handler.py


"""app/apis/views/front_end_handler.py
"""
from flask import jsonify, render_template

from app import secret_key


def handler(req):
    """handler
    """
    param1 = req.get('param1')
    param2 = req.get('param2')

    if param1 == 'app_form':
        return _app_form(req=param2)

    return jsonify({'message': 'no route matched with those values'}), 200


def _app_form(req):
    """_app_form
    """
    if req.get('secret_key', '') != secret_key:
        return jsonify({'message': 'no route matched with those values'}), 200
    return render_template('app_form.html', secret_key=req.get('secret_key', ''))

front-end layout

app_form.html


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>raspi-streaming</title>

    <style type="text/css">
        html,
        body {
            -webkit-user-select: none;
            width: 100%;
            height: 100%;
        }

        table {
            width: 100%;
            height: 100%;
        }

        table,
        td {
            border: 1px gray solid;
            padding: 10px;
        }

        img.img-option {
            width: 100%;
            /* height: 100%; */
        }
    </style>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
    // nothing to do
    </script>
</head>

<body>
    <table>
        <tr height="5%">
            <td>
                <h1>raspi-streaming</h1>
            </td>
        </tr>
        <tr>
            <td>
                <img class="img-option"
                    src="{{ url_for('raspi-streaming.api', process='back_end', request='video_feed', secret_key=secret_key) }}">
            </td>
        </tr>
    </table>
</body>

</html>

back-end

target.sh


/app
└── apis
     └── views
         ├── back_end_handler.py
         └── camera.py

back-end control

back_end_handler.py


"""app/apis/views/back_end_handler.py
"""
from flask import Response, jsonify

from app import secret_key
from app.apis.views.camera import Camera


def handler(req):
    """handler
    """
    param1 = req.get('param1')
    param2 = req.get('param2')

    if param1 == 'video_feed':
        return _video_feed(req=param2)

    return jsonify({'message': 'no route matched with those values'}), 200


def _video_feed(req):
    """_video_feed
    """
    if req.get('secret_key', '') != secret_key:
        return jsonify({'message': 'no route matched with those values'}), 200
    return Response(_generator(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')


def _generator(camera):
    """_generator
    """
    while True:
        frame = camera.frame()
        yield b'--frame\r\n'
        yield b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n'

Camera control

camera.py


"""app/apis/views/camera.py
"""
import cv2


class Camera():
    """Camera
    """

    def __init__(self):
        self.video_capture = cv2.VideoCapture(-1)

    def __del__(self):
        self.video_capture.release()

    def frame(self):
        """frame
        """
        _, frame = self.video_capture.read()
        _, image = cv2.imencode('.jpeg', frame)
        return image.tobytes()

Recommended Posts

Create a web surveillance camera with Raspberry Pi and OpenCV
I tried to make a motion detection surveillance camera with OpenCV using a WEB camera with Raspberry Pi
Create a color sensor using a Raspberry Pi and a camera
A memorandum when making a surveillance camera with Raspberry Pi
I made a surveillance camera with my first Raspberry PI.
Create a car meter with raspberry pi
How to make a surveillance camera (Security Camera) with Opencv and Python
Detect mask wearing status with OpenCV and Raspberry Pi
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Troubleshoot with installing OpenCV on Raspberry Pi and capturing
Display USB camera video with Python OpenCV with Raspberry Pi
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server --2 PHP introduction
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a Web server ―― 1. Apache introduction
Python beginner opens and closes interlocking camera with Raspberry Pi
Source compile Apache2.4 + PHP7.4 with Raspberry Pi and build a web server --3. Use MySQL
Create an LCD (16x2) game with Raspberry Pi and Python
I tried connecting Raspberry Pi and conect + with Web API
Create a partition and then install the Raspberry Pi OS
Using a webcam with Raspberry Pi
I made a web server with Raspberry Pi to watch anime
Create a striped illusion with gamma correction for Python3 and openCV3
Christmas classic (?) Lighting a Christmas tree with Raspberry Pi and Philips Hue
Make a thermometer with Raspberry Pi and make it viewable with a browser Part 4
Make a Kanji display compass with Raspberry Pi and Sense Hat
Pet monitoring with Rekognition and Raspberry pi
[Raspberry Pi] Add a thermometer and a hygrometer
Build a Tensorflow environment with Raspberry Pi [2020]
Create a simple web app with flask
Make a wash-drying timer with a Raspberry Pi
Create a web service with Docker + Flask
Operate an oscilloscope with a Raspberry Pi
Create your own virtual camera with Python + OpenCV and apply original effects
Make a wireless LAN Ethernet converter and simple router with Raspberry Pi
Create a socket with an Ethernet interface (eth0, eth1) (Linux, C, Raspberry Pi)
Create a web map using Python and GDAL
MQTT RC car with Arduino and Raspberry Pi
Launch a web server with Python and Flask
Create a visitor notification system using Raspberry Pi
Get temperature and humidity with DHT11 and Raspberry Pi
Make a thermometer with Raspberry Pi and make it visible on the browser Part 3
Cross-compiling Raspberry Pi and building a remote debugging development environment with VS Code
Creating a temperature control system with Raspberry Pi and ESP32 (3) Recipient Python file
[For beginners] I made a motion sensor with Raspberry Pi and notified LINE!
I tried to create a button for Slack with Raspberry Pi + Tact Switch
Build a distributed environment with Raspberry PI series (Part 3: Install and configure dnsmasq)
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
GPGPU with Raspberry Pi
Raspberry Pi video camera
Gently explain the process of making a simple serverless surveillance camera using Raspberry Pi, Gmail API and Line API
DigitalSignage with Raspberry Pi
Record temperature and humidity with systemd on Raspberry Pi
Machine learning with Raspberry Pi 4 and Coral USB Accelerator
Easy IoT to start with Raspberry Pi and MESH
Create a native GUI app with Py2app and Tkinter
Display images taken with the Raspberry Pi camera module
Measure temperature and humidity with Raspberry Pi3 and visualize with Ambient
Create a batch of images and inflate with ImageDataGenerator
Create a 3D model viewer with PyQt5 and PyQtGraph
Face detection from images taken with Raspberry Pi camera
Getting Started with Yocto Project with Raspberry Pi 4 and WSL2
[Linux] Create a self-signed certificate with Docker and apache