[python] Send the image captured from the webcam to the server and save it

Overview

Implement the following: ・ Launch the webcam in the browser ・ Capture the image of the camera screen -Send the captured image to the server and save it

Folder structure

/home/capture_img
|--run.py
|--app
|  |--api.py
|  |--service.py
|  |--static
|  |  |--main.js
|  |--templates
|  |  |--index.html
|--images #Where to save the captured image

Source code

run.py

run.py


from app.api import api

if __name__ == '__main__':
    api.run(host='0.0.0.0', port=8000)

app/api.py

app/api.py


from flask import Flask, request, make_response, render_template, url_for

from . import service

api = Flask(__name__)

@api.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@api.route('/capture_img', methods=['POST'])
def capture_img():
    msg = service.save_img(request.form["img"])
    return make_response(msg)

app/service.py

app/service.py


import base64
import numpy as np
import cv2

def save_img(img_base64):
    #binary <- string base64
    img_binary = base64.b64decode(img_base64)
    #jpg <- binary
    img_jpg=np.frombuffer(img_binary, dtype=np.uint8)
    #raw image <- jpg
    img = cv2.imdecode(img_jpg, cv2.IMREAD_COLOR)
    #Path to save the decoded image
    image_file="/home/capture_img/images/img0000.jpg "
    #Save image
    cv2.imwrite(image_file, img)
    return "SUCCESS"

templates/index.html

templates/index.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>get_capture</title>
</head>
<body>
    <h3>Capture capture by pressing the space key</h3>
    <video id="video" width="640" height="480" autoplay></video>
    <canvas id="canvas" class="canvas-wrapper"></canvas>
</body>

<script src="{{url_for('static', filename='main.js')}}"></script>

<style>
    /*Hide canvas*/
    #canvas {
        display: none !important;
    }
</style>
</html>

static/main.js

static/main.js


var video = document.getElementById('video');
// getUserMedia()Get camera footage with
var media = navigator.mediaDevices.getUserMedia({ video: true });
//Pour into video tags for real-time playback (streaming)
media.then((stream) => {
    video.srcObject = stream;
});

var canvas = document.getElementById('canvas');
canvas.setAttribute('width', video.width);
canvas.setAttribute('height', video.height);

video.addEventListener(
    'timeupdate',
    function () {
        var context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, video.width, video.height);
    },
    true
);

//Set the listener that executes capture acquisition when the space key is pressed
document.addEventListener('keydown', (event) => {
    var keyName = event.key;
    if (keyName === ' ') {
        console.log(`keydown: SpaceKey`);
        context = canvas.getContext('2d');
        //Remove the head of the acquired base64 data
        var img_base64 = canvas.toDataURL('image/jpeg').replace(/^.*,/, '')
        captureImg(img_base64);
    }
});

var xhr = new XMLHttpRequest();

//Captured image data(base64)POST
function captureImg(img_base64) {
    const body = new FormData();
    body.append('img', img_base64);
    xhr.open('POST', 'http://localhost:8000/capture_img', true);
    xhr.onload = () => {
        console.log(xhr.responseText)
    };
    xhr.send(body);
}

Installation of required modules

root@ed9f7bedad16:/# pip install opencv-python flask

Run

root@ed9f7bedad16:/# python /home/capture_img/run.py
 * Serving Flask app "app.api" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)

Operation check

Access http: // localhost: 8000 & press spacebar

スクリーンショット 2020-10-16 23.50.02.png

root@ed9f7bedad16:/# ls /home/capture_img/images/
img0000.jpg

The captured image has been saved. img0000.jpg

that's all.

Recommended Posts

[python] Send the image captured from the webcam to the server and save it
Start the webcam to take a still image and save it locally
Send a message from Slack to a Python server
I want to cut out only the face from a person image with Python and save it ~ Face detection and trimming with face_recognition ~
Output the report as PDF from DB with Python and automatically attach it to an email and send it
[Free] Hit the Clash Royale API from lambda and send it to LINE
Send log data from the server to Splunk Cloud
Build a Python environment and transfer data to the server
POST the image selected on the website with multipart / form-data and save it to Amazon S3! !!
I made a server with Python socket and ssl and tried to access it from a browser
Return the image data with Flask of Python and draw it to the canvas element of HTML
Send image with python, save with php
Install mecab on Sakura shared server and call it from python
[Python] Try to graph from the image of Ring Fit [OCR]
How to get followers and followers from python using the Mastodon API
Terminal association from the server side to Amazon SNS (python + boto3)
Convert the result of python optparse to dict and utilize it
Operate Firefox with Selenium from python and save the screen capture
Read the old Gakushin DC application Word file (.doc) from Python and try to operate it.
Send a message from Python to Slack
Push notification from Python server to Android
Porting and modifying doublet-solver from python2 to python3.
Try using the Python web framework Django (1)-From installation to server startup
Send and receive image data as JSON over the network with Python
Python --Get bitcoin rate BTC / JPY from bitflyer at regular intervals and save it to a file
Pass the selected item in Tablacus Explorer from JScript to python and rename it all at once
I ran GhostScript with python, split the PDF into pages, and converted it to a JPEG image.
The story of making a tool to load an image with Python ⇒ save it as another name
[Python] How to save the installed package and install it in a new environment at once Mac environment
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
I want to pass an argument to a python function and execute it from PHP on a web server
Image characters and post to slack (python slackbot)
python Binary search It is surprisingly easy to implement bisect.bisect_left and bisect.bisect_right from 0
Organize the flow from granting permissions to python users to make migrations and migrating
[Python] How to read data from CIFAR-10 and CIFAR-100
Use Pillow to make the image transparent and overlay only part of it
Send messages to Skype and Chatwork in Python
POST images from ESP32-CAM (MicroPython) to the server
Crop Numpy.ndarray and save it as an image
GAE --With Python, rotate the image based on the rotation information of EXIF and upload it to Cloud Storage.
[Python] I will upload the FTP to the FTP server.
[Python3] Take a screenshot of a web page on the server and crop it further
Extract images and tables from pdf with python to reduce the burden of reporting
I want to replace the variables in the python template file and mass-produce it in another file.
[Note] How to write QR code and description in the same image with python
It is easy to execute SQL with Python and output the result in Excel
Pass an array from PHP to PYTHON and do numpy processing to get the result
[Python] How to remove duplicate values from the list
The wall of changing the Django service from Python 2.7 to Python 3
How to scrape image data from flickr with python
I tried to detect the iris from the camera image
Clear the cron.log regularly to prevent it from growing.
[Python] Specify the range from the image by dragging the mouse
Convert the image in .zip to PDF with Python
I wanted to use the Python library from MATLAB
Send data from Python to Processing via socket communication
Send and receive Gmail via the Gmail API using Python
The first step to getting Blender available from Python
Get mail from Gmail and label it with Python3
Rotate and scale the image before cropping [python] [OpenCV]
POST the image with json and receive it with flask