Send and receive image data as JSON over the network with Python

Introduction

I wrote a code several times to send the image taken by the webcam to another server running the face detection model etc. via HTTP communication, so make a note so that you do not forget it. In the sample code, the image taken from the Web camera on the sending side is sent to the server at regular intervals, the face is detected on the receiving side, a box is drawn, and the image file is saved locally.

Sender

sender.py


import numpy as np
import cv2
import time
import json
import base64
import requests

def send_image(img):
  #Convert image to sendable format and store in JSON
  _, encimg = cv2.imencode(".png ", img)
  img_str = encimg.tostring()
  img_byte = base64.b64encode(img_str).decode("utf-8")
  img_json = json.dumps({'image': img_byte}).encode('utf-8')
  
  #Send HTTP request
  response = requests.post("http://localhost:8080/save", data=img_json)
  print('{0} {1}'.format(response.status_code, json.loads(response.text)["message"]))

if __name__ == '__main__':
  cap = cv2.VideoCapture(0)
  cap.set(cv2.CAP_PROP_FPS, 30)
  i = 0
  while True:
    _, img = cap.read()
    if i % 5 == 0:
      send_image(img)
    i += 1

Receiver

receiver.py


import os
import json
import cv2
import base64
import numpy as np
from datetime import datetime
from flask import Flask, request, Response
app = Flask(__name__)
count = 0

#Create a folder to save images
image_dir = "./images"
if not os.path.isdir(image_dir):
  os.mkdir(image_dir)

def detect_face(img):
  #Face detection model ('haarcascade_frontalface_default.xml') Can be downloaded from the link below
  # https://github.com/opencv/opencv/tree/master/data/haarcascades
  face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
  faces = face_cascade.detectMultiScale(img, 1.3, 5)
  return faces

@app.route('/save', methods=['POST'])
def save_image():
    #Data conversion process
    data = request.data.decode('utf-8')
    data_json = json.loads(data)
    image = data_json['image']
    image_dec = base64.b64decode(image)
    data_np = np.fromstring(image_dec, dtype='uint8')
    decimg = cv2.imdecode(data_np, 1)

    #Detect face and draw box
    gray_img = cv2.cvtColor(decimg, cv2.COLOR_BGR2GRAY)
    faces = detect_face(gray_img)
    for (x,y,w,h) in faces:
      decimg = cv2.rectangle(decimg,(x,y),(x+w,y+h),(255,0,0),2)
    
    #Save image file
    global count
    filename = "./images/image{}.png ".format(count)
    cv2.imwrite(filename, decimg)
    count += 1

    #Send HTTP response
    return Response(response=json.dumps({"message": "{} was saved".format(filename)}), status=200)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

reference

http://edosha.hatenablog.jp/entry/2017/09/05/174453 https://ysss.hateblo.jp/entry/2018/07/31/053507

Recommended Posts

Send and receive image data as JSON over the network with Python
POST the image with json and receive it with flask
Read JSON with Python and output as CSV
Send and receive binary data via serial communication with python3 (on mac)
Send and receive Gmail via the Gmail API using Python
Read json data with python
Solve the spiral book (algorithm and data structure) with python!
Send and receive data with MQTT via Watson IoT Platform
Neural network with OpenCV 3 and Python 3
JSON encoding and decoding with python
Return the image data with Flask of Python and draw it to the canvas element of HTML
Send image with python, save with php
[Python3] Save the mean and covariance matrix in json with pandas
Data pipeline construction with Python and Luigi
Receive textual data from mysql with python
HTML email with image to send with python
POST variously with Python and receive with Flask
Convert Excel data to JSON with python
Reading and writing JSON files with Python
Try to image the elevation data of the Geographical Survey Institute with Python
[python] Send the image captured from the webcam to the server and save it
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
I tried "differentiating" the image with Python + OpenCV
Just add the python array to the json data
Receive and display HTML form data in Python
Execute raw SQL using python data source with redash and display the result
Let's play with Python Receive and save / display the text of the input form
I tried "binarizing" the image with Python + OpenCV
Load the network modeled with Rhinoceros in Python ②
I'm addicted to the difference in how Flask and Django receive JSON data
[Python3] Read and write with datetime isoformat with json
Solving the Lorenz 96 model with Julia and Python
Archive and compress the entire directory with python
POST JSON in Python and receive it in PHP
Load the network modeled with Rhinoceros in Python ①
Template network config generation with Python and Jinja2
Start communication with UDP and send and receive with TCP
Display the image after Data Augmentation with Pytorch
Acquire the data of Mitsubishi UFJ International Investment Trust eMAXIS with Python and make a graph with the beginning of the term as 100
[Note] How to write QR code and description in the same image with python
Extract the table of image files with OneDrive & Python
Receive the form in Python and do various things
Notes on HDR and RAW image processing with Python
[Python] Get the numbers in the graph image with OCR
Visualize the range of interpolation and extrapolation with python
Convert the image in .zip to PDF with Python
Get comments and subscribers with the YouTube Data API
Install the latest stable Python with pyenv (both 2 and 3)
Read json file with Python, format it, and output json
Specify MinGW as the compiler to use with Python
Rotate and scale the image before cropping [python] [OpenCV]
Investigate Java and python data exchange with Apache Arrow
Extract the band information of raster data with python
Data analysis with python 2
[Python] Use JSON with Python
Image processing with Python
Send email with Python
Data analysis with Python
I tried the same data analysis with kaggle notebook (python) and Power BI at the same time ②
I tried the same data analysis with kaggle notebook (python) and Power BI at the same time ①
I tried to find the entropy of the image with python