• Stars
    star
    194
  • Rank 200,219 (Top 4 %)
  • Language
    Python
  • License
    GNU General Publi...
  • Created over 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Stream images from a connected camera over MQTT, view using Streamlit, record to file and sqlite

mqtt-camera-streamer

Summary: Publish frames from a connected camera or MJPEG/RTSP stream to an MQTT topic, and view the feed in a browser on another computer with Streamlit.

Long introduction: A typical task in IOT/science is that you have a camera connected to one computer and you want to view the camera feed on a second computer, and maybe preprocess the images before saving them to disk. I have always found this to be way more effort than expected. In particular, working with camera streams can get quite complicated and may lead you to experiment with tools like Gstreamer and ffmpeg that have a steep learning curve. In contrast, working with MQTT is very straightforward and is often familiar to anyone with an interest in IOT. This repo, mqtt-camera-streamer uses MQTT to send frames from a camera over a network at low frames-per-second (FPS). A viewer is provided for viewing the camera stream on any computer on the network. Frames can be saved to disk for further processing. Also it is possible to setup an image processing pipeline by linking MQTT topics together, using an on_message(topic) to do some processing and send the processed image downstream on another topic.

Note that this is not a high FPS solution, and in practice I achieve around 1 FPS which is practical for IOT experiments and tasks such as preprocessing (cropping, rotating) images prior to viewing them. This code is written for simplicity and ease of use, not high performance.

Installation

Install system wide on an RPi, or on other OS use a venv to isolate your environment, and install the required dependencies:

$ (base) python3 -m venv venv
$ (base) source venv/bin/activate
$ (venv) pip3 install -r requirements.txt

Listing cameras with OpenCV

The check-opencv-cameras.py script assists in discovering which cameras OpenCV can connect to on your computer (does not work with RPi camera). If your laptop has a built-in webcam this will generally be listed as VIDEO_SOURCE = 0. If you plug in an external USB webcam this takes precedence over the built-in webcam, with the external camera becoming VIDEO_SOURCE = 0 and the built-in webcam becoming VIDEO_SOURCE = 1.

To check which OpenCV cameras are detected run:

$ (venv) python3 scripts/check-opencv-cameras.py

Configuration using config.yml

Use the config.yml file in the config directory to configure your system. If your desired camera is listed as source 0 you will configure video_source: 0. Alternatively you can configure the video source as an MJPEG or RTSP stream. For example in config.yml you may configure something like video_source: "rtsp://admin:[email protected]:554/11" for a commercial RTSP camera. To configure a RPi camera running the web_streaming.py example you configure video_source: http://pi_ip:8000/stream.mjpg

Validate the config can be loaded by running:

$ (venv) python3 scripts/validate-config.py

Note that this script does not check the accuracy of any of the values in config.yml, just that the file path is correct and the file structure is OK.

By default scripts/opencv-camera.py will look for the config file at ./config/config.yml but an alternative path can be specified using the environment variable MQTT_CAMERA_CONFIG. You can set this using export MQTT_CAMERA_CONFIG=/home/pi/github/mqtt-camera-streamer/config/config.yml

Publish camera frames

To publish camera frames with OpenCV over MQTT:

$ (venv) python3 scripts/opencv-camera-publish.py

Camera display

To view the camera stream with Streamlit:

$ (venv) streamlit run scripts/viewer.py

Note: if Streamlit becomes unresponsive, ctrl-z to pause Streamlit then kill -9 %%. Also note that the viewer can be run on any machine on your network.

Save frames

To save frames to disk:

$ (venv) python3 scripts/save-captures.py

Save frames to db

As save-captures.py but in addition saving the frame thumbnail to a sqlite db:

$ (venv) python3 scripts/db-recorder.py

The images can be viewed using sqlite browser

If you wish to run a server with UI for browsing the images then datasette with the datasette-render-images plugin can be used.

$ (venv) pip install datasette
$ (venv) pip install datasette-render-images
$ (venv) datasette captures/records.db

Image processing pipeline

To process a camera stream (the example rotates the image):

$ (venv) python3 scripts/processing.py

Home Assistant

You can view the camera feed using Home Assistant and configuring an MQTT camera. Add to your configuration.yaml:

camera:
  - platform: mqtt
    topic: homie/mac_webcam/capture
    name: mqtt_camera
  - platform: mqtt
    topic: homie/mac_webcam/capture/rotated
    name: mqtt_camera_rotated
  - platform: mjpeg # the raw mjpeg feed if using picamera
    name: picamera
    mjpeg_url: http://192.168.1.134:8000/stream.mjpg

MQTT

Need an MQTT broker? If you have Docker installed I recommend eclipse-mosquitto. A basic broker can be run with:

docker run -p 1883:1883 -d eclipse-mosquitto

Note that I have structured the MQTT topics following the homie MQTT convention, linked in the references. This is not necessary but is best practice IMO.

OpenCV & streamlit on RPi

OpenCV is used to read the images from a connected camera or MJPEG/RTSP stream. On a Raspberry pi (RPi) installing OpenCV can be troublesome, and I found it necessary to first sudo apt-get install libatlas-base-dev libjasper-dev libqtgui4 python3-pyqt5 libqt4-test libilmbase-dev libopenexr-dev libgstreamer1.0-dev libavcodec58 libavformat58 libswscale5 before installing opencv using the instructions below. Likewise Streamlit can be challenging to install on an RPi, and if you dont need it then remove it from requirements.txt. If you do wish to install Streamlit on the RPi see this thread for latest guidance. On 24/3/2021 I was able to install opencv-python==4.5.1.48 but not streamlit on an RPi4 32bit.

RPi camera

Use an official RPi camera and ensure picamera is installed with pip3 install picamera. If you use the RPi in desktop mode you can check the camera feed using raspistill -o image.jpg. Use the official web_streaming example which creates an mjpeg stream on http://pi_ip:8000/stream.mjpg. This mjpeg stream can be configured as a source with mqtt-camera-streamer to translate the mjepg stream to an mqtt stream.

RPi service

You can run any of the scripts as a service, which means they will automatically start on RPi boot, and can be easily started & stopped. Create the service file in the appropriate location on the RPi using:

sudo nano /etc/systemd/system/my_script.service

Entering the following (adapted for your script.py file location and args, assumes you are using system python3):

[Unit]
Description=Service for mqtt-camera-publish
After=network.target

[Service]
ExecStart=/usr/bin/python3 -u opencv-camera-publish.py
WorkingDirectory=/home/pi/github/mqtt-camera-streamer/scripts
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target

Once this file has been created you can to start the service using: sudo systemctl start my_script.service

View the status and logs with: sudo systemctl status my_script.service

Stop the service with: sudo systemctl stop my_script.service

Restart the service with: sudo systemctl restart my_script.service

You can have the service auto-start on rpi boot by using: sudo systemctl enable my_script.service

You can disable auto-start using: sudo systemctl disable my_script.service

References

More Repositories

1

HASS-Deepstack-object

Home Assistant custom component for using Deepstack object detection
Python
411
star
2

Hue-sensors-HASS

Support for Hue motion sensors and device tracker
Python
347
star
3

fire-detection-from-images

Detect fire in images using neural nets
Jupyter Notebook
284
star
4

HASS-Deepstack-face

Home Assistant custom component for using Deepstack face recognition
Jupyter Notebook
202
star
5

HASS-data-detective

Explore and analyse your Home Assistant data
Python
183
star
6

yolov5-flask

Official implementation at https://github.com/ultralytics/yolov5/tree/master/utils/flask_rest_api
Python
155
star
7

deepstack-ui

UI for working with Deepstack
Python
121
star
8

HASS-plate-recognizer

Read number plates with https://platerecognizer.com/
Python
86
star
9

HASS-amazon-rekognition

Home Assistant Object detection with Amazon Rekognition
Jupyter Notebook
84
star
10

Useful-python

Python code and notebooks for reference
Jupyter Notebook
76
star
11

tensorflow-lite-rest-server

Expose tensorflow-lite models via a rest API using FastAPI
Jupyter Notebook
73
star
12

object-detection-app

Simple object detection app with streamlit
Python
73
star
13

coral-pi-rest-server

Perform inferencing of tensorflow-lite models on an RPi with acceleration from Coral USB stick
Jupyter Notebook
61
star
14

rpi-enviro-mqtt

Send air quality data from a Pimoroni RPi Enviro+ over MQTT
Jupyter Notebook
43
star
15

streamlit-image-juxtapose

A simple Streamlit Component to compare images in Streamlit apps. It integrates Knightlab's JuxtaposeJS
Python
33
star
16

HASS-Sighthound

Beta features for Home Assistant Sighthound integration
Python
33
star
17

Hue-remotes-HASS

PLEASE READ THE README
Python
31
star
18

Useful-python-for-medical-physics

Scripts that have been useful. Includes some analysis of EGSnrc 3ddose files
Jupyter Notebook
24
star
19

HASS-Machinebox-Facebox

Home Assistant face detection using Machinebox.io
Jupyter Notebook
24
star
20

HASS-Google-Vision

Instead use https://github.com/robmarkcole/HASS-amazon-rekognition
Jupyter Notebook
21
star
21

HASS-Machinebox-Classificationbox

Home-Assistant image classification using Machinebox.io
Jupyter Notebook
21
star
22

HASS-Google-Coral

RETIRED - instead use https://github.com/robmarkcole/HASS-Deepstack-object
Jupyter Notebook
18
star
23

text-insights-app

Upload an image of a document and extract text, names, facts and figures
Python
18
star
24

streamlit-segmentation-app

streamlit app for binary segmentation
Python
17
star
25

HASS-S3

Home Assistant integration for S3
Python
16
star
26

kaggle-ships-in-Google-Earth-with-YOLOv8

Applying YOLOv8 to Kaggle Ships in Google Earth dataset
Jupyter Notebook
16
star
27

HASS-Google-Cloud-SQL

Guide on using Google Cloud SQL as a database recorder for Home-assistant
Jupyter Notebook
15
star
28

bme680-mqtt

Publish bme680 data via MQTT
Python
14
star
29

bme680-mqtt-micropython

Publish data from the bme680 sensor over MQTT using micropython
Python
14
star
30

HASS-amazon-rekognition-text

Home Assistant integration to extract text from digital and mechanical displays using AWS rekognition
Python
14
star
31

HASS-Deepstack-scene

Home Assistant custom integration for using Deepstack scene recognition
Python
13
star
32

HASS-data-science

Data science with Home-assistant
Jupyter Notebook
13
star
33

robins-homeassistant-config

My Home-assistant config
Python
13
star
34

deepstack-python

Unofficial python API for DeepStack
Jupyter Notebook
12
star
35

python-scripts-for-home-assistant

Python scripts for use with the home-assistant python_scripts component
Python
11
star
36

TrasportAPI-HASS

UK bus & train status TransportAPI Home-assistant component ADDED TO HA
Jupyter Notebook
11
star
37

hassio-addons

Addons for Home Assistant
Dockerfile
10
star
38

robins-hassio-config

My home-assistant config from my experimental hassio instance
10
star
39

satellite-imagery-projects

Jupyter Notebook
10
star
40

HASS-filesize-sensor

Custom component for displaying the size (in MB) of files - ADDED TO HA 0.64
Jupyter Notebook
10
star
41

yolov5-fastapi

FastAPI app exposing yolov5 object detection
Python
10
star
42

simple-fastAPI-webapp

Use fastAPI to generate html web app that will serve a local directory or S3 bucket of images
Python
10
star
43

HASS-Clarifai

Home-Assistant image tagging with Clarifai https://clarifai.com/developer/guide/
Jupyter Notebook
9
star
44

HASS-BBC-envirobit

Stream sensor readings from the BBC micropython envirobit to Home-Assistant
Python
9
star
45

Medical_physics_imageJ

Scripts and plugins for performing analysis of images in imageJ
Python
9
star
46

deepstack-analytics

Analytics with deepstack
Jupyter Notebook
9
star
47

HASS-hammerspoon

hammerspoon script to toggle a Home-assistant switch on wake/sleep of my MacBook
Lua
8
star
48

HASS-circuitpython-air-quality-sensor-node

A circuitpython board with various air quality sensors, data processed by Home Assistant
Jupyter Notebook
8
star
49

HASS-kalman-filter

Home-Assistant custom integration adding a 1D Kalman filter
Jupyter Notebook
8
star
50

pan-tilt-hat-HASS

Custom component adding the pimoroni pan-tilt-hat to Home-assistant: tested in HA 0.94 ok
Python
7
star
51

tensorflow_files_for_home_assistant_component

All the files you need for the Home-Assistant tensorflow component
Python
7
star
52

arxiv-github-scanner

Streamlit app for querying the arxiv api
Python
5
star
53

London-tube-status

Fetch the tube status in a python dictionary
Jupyter Notebook
5
star
54

HASS-folder-sensor

Home-assistant custom component for monitoring the contents of a folder - ADDED TO HA 0.64
Jupyter Notebook
5
star
55

circuitpython-on-home-assistant

Programming and managing circuitpython boards from Home-Assistant
Python
5
star
56

HASS-Machinebox-Tagbox

Home-Assistant custom integration for image tag detection using Tagbox
Python
5
star
57

aerotech

Class to enable control of the Ensemble controllers by Aerotech using TCP
Jupyter Notebook
5
star
58

HASS-rest-image-process

Home-assistant component for image processing via local REST API machinebox.io
Python
4
star
59

aws-lambda-pytorch-image-classification-example

Example of implementing a pytorch image classifier service using AWS lambda
Python
4
star
60

streamlit-codespace

tryout Streamlit in a Github Codespace
4
star
61

wildlife-camera-trap-data-visualsation-app

Visualise wildlife camera trap data
4
star
62

robmarkcole

3
star
63

Hue-sensors

Standalone package for parsing the Hue API data for Hue sensors
Jupyter Notebook
3
star
64

streamlit-image-table-pandas-app

Place images in a table using pandas and generate a shareable report
HTML
3
star
65

HASS-Yolo

Object detection in Home-Assistant using Yolo
3
star
66

RF-doorbell-serial

Using an Arduino with RF receiver to detect when my doorbell has been pressed
Arduino
3
star
67

arduino-tensorflow-example

Code and results from https://medium.com/p/7daf95b4157
C
3
star
68

HASS-data-detective-analysis

Analysis using the HASS-data-detective package
Jupyter Notebook
3
star
69

tagbox_python

A python script to teach Machinebox/Tagbox
Python
2
star
70

fastpages-blog

My blog
Jupyter Notebook
2
star
71

fastAPI-chatGPT-experiment

Use chatGPT to create a simple fastAPI app
Python
2
star
72

quickstart-with-geotiffs

A quickstart guide to working with geotiffs
Jupyter Notebook
2
star
73

rpi-rf-mqtt

Monitor a 433 MHz signal and post to an MQTT topic - WIP - do not use
Python
2
star
74

yolov5-ui

Web ui for yolov5 using Streamlit
Python
2
star
75

jupyter-codespace

Tryout running jupyter notebooks in a Github Codespace
Jupyter Notebook
2
star
76

jupyterlite-playground

Jupyter Notebook
2
star
77

London-Air-Quality

Queries the London air quality data feed provided by Kings College London
Jupyter Notebook
2
star
78

HASS-Photo-browser

Instead use media_dirs: local: /config/images/
Jupyter Notebook
2
star
79

classificationbox_python

Python script for teaching Classificationbox image classes
Jupyter Notebook
2
star
80

simplehound

Unofficial python API for Sighthound Cloud
Jupyter Notebook
1
star
81

HASS-mqtt-camera-forwarder

Custom integration which forwards a camera feed onto an MQTT topic
Python
1
star
82

Hue-sensors-phue

Identical to Hue-sensors but using the phue package
Jupyter Notebook
1
star
83

robins-google-colaboratory

My Google CoLaboratory notebooks
Jupyter Notebook
1
star
84

google-app-engine-flask-example

Working through Building a Python 3 App on App Engine tutorial
Dockerfile
1
star
85

artist-classification-with-ML

Train an "off-the-shelf" deep image network with color images of Impressionist paintings from the web (Seurat, Signac, Monet, Degas, Renoir, ...) for classification of both artist and simple subject matter
Jupyter Notebook
1
star
86

HASS-SigFox

SigFox component for Home-Assistant
Jupyter Notebook
1
star
87

reproducible-satellite-image-analysis

Use Binder for reproducible satellite image analysis
Jupyter Notebook
1
star
88

water-sensor-micropython

Simple micropython script to detect water using a dirt cheap sensor
Python
1
star
89

HASS-rest-camera

Custom component for a camera which displays images served by a REST API
Python
1
star
90

umap-image-embedding-streamlit-app

App to explore umap image embeddings for MNIST class datasets
Jupyter Notebook
1
star