当前位置:网站首页>1、 Transmission of file stream on Web page
1、 Transmission of file stream on Web page
2022-07-29 06:08:00 【My hair is messy】
One 、flask.request.files[‘file’] Method
Flask Of files Method can be used to transfer all kinds of documents , Take video transmission as an example .
- Client code :( Focus on files Assembly method )
file type : The document passed over is the type of dictionary (files = {‘file’:img_data})
Picture data :binary( Binary system ) Type upload .
file type : The document passed over is the type of dictionary (files = {'file':img_data})
import requests
import json
#todo use open Read
with open('./666051400.mp4','rb') as f:
video_data = f.read() # type : <class 'bytes'>
files = {
'file':video_data,"card_json":open(json_path,'rb'),}
data = {
'video_type':'mp4','unique_msg':'yfqtest0328','add_sign':0}
r = requests.post('http://127.0.0.1:8000/searchmp4', data, files=files) # Be sure to point out files=files
print(json.loads(r.text))
#todo use opencv Read
img=cv2.imread(path,cv2.IMREAD_COLOR)
imgRGB=cv2.cvtColor(img,cv2.IMREAD_COLOR) # turn rgb Actually, it's OK not to transfer , Skip this step directly
r,buf=cv2.imencode(".jpg",imgRGB) # Image coding
bytes_image=Image.fromarray(np.uint8(buf)).tobytes() #array convert to image Re turn bytes
files = {
'file': bytes_image}
r = requests.post(url, files=files)
print(r.text)
- Server code :( Focus on files Receiving method )
import json,requests
import base64
import numpy as np
from PIL import Image
import flask
import io,cv2
from io import BytesIO,StringIO
app=flask.Flask(__name__)
@app.route("/",methods=["GET","POST"])
def registered_user():
print("wo")
try:
if request.method == "POST":
video_type = request.form.get('video_type')
video_data.save('123.mp4')
get_file=flask.request.files["file"] # Upload files ---><FileStorage: '71e630263c7ac3eb967420224c63bec.png' ('image/png')>
pic=get_file.read() # Read the content , A lot of crap <class 'bytes'>
user_image=Image.open(BytesIO(pic)) #BytesIO It can read and write in memory bytes
arry_image=np.array(user_image)
# cv2.imwrite("query.jpg",arry_image) # Save to local
# '.jpg' Means to put the current picture img according to jpg Format encoding
pic1=cv2.imencode(".jpg",arry_image)[1].tostring() #.tostring() take number Object to string
pic2=base64.b64encode(pic1) # Use base64 Encode byte like objects s, And return a byte object .
register_data={
"Pic":pic2.decode()}
data=json.dumps(register_data) # Will a Python The data structure is converted to JSON
url='http://localhost:8888/detect_line'
r=requests.post(url,data) # send out post request
return json.loads(r.content)["results"] # The output file is json Format output in this format .
except Exception as e:
import logging
logging.exception(e)
return "error"
# The above is the data conversion
Two 、flask.request.get_data() Method
Flask Of get_data() Method can be used to transmit pictures as an example .
- Client code
Picture data : Turn the picture into base64 data type
File data :json Upload in file form .register_data = {'Pic': pic.decode(), 'Card_Json': json_file}
def cv_imread(file_path):
# Read Chinese path
cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1)
return cv_img
path=r"/data2/enducation/answer_card/answer-card-recognition/pic/2021-08-17_14_16_18.jpg"
pic = main.cv_imread(path)
pic = cv_imread(path)
pic = np.asarray(pic) # turn nparry
pic = cv2.imencode('.jpg', pic)[1].tobytes() # Use UTF-8 code , Re turn bytes
#json Only string format transmission is supported , So use base64 code , This process is a little time-consuming 0.5s about
pic = base64.b64encode(pic)
# print(path.replace("jpg" or "png" or "JPG","json"))
if os.path.exists(path.replace("jpg","json")):
with open(path.replace("jpg","json"), 'r') as f:
line=json.load(f)
try:
json_file=eval(line)
except:
json_file=line
else:
json_file=None
register_data = {
'Pic': pic.decode(), 'Card_Json': json_file}
data = json.dumps(register_data) #python Data transfer json
r = requests.post(url, data)
para = json.loads(r.content) # So does the value returned json
print(para['answer'])
print(para['idNumber'])
- Server code
paras = json.loads(flask.request.get_data()) # Get json file (pic,json) And read
# Take out the picture
pic = paras['Pic']
user_image = base64.b64decode(pic) # decode base64
img_array = np.fromstring(user_image, np.uint8) # Decode from the string arry Type data
# cv2.imwrite('query.jpg', img_array)
img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB) # Decode and transfer rgb
# Take out json file
json_handle = paras['Card_Json']
try:
json_handle = eval(json_handle)
except:
json_handle = json_handle
Here are some format transformations `.
import base64
import numpy as np
import requests as req
from PIL import Image
from io import BytesIO
import re
import cv2
# ???????url????????PIL Image????
def url_to_PIL_Image(img_url):
response = req.get(img_url)
image = Image.open(BytesIO(response.content))
return image
# ?base64??????PIL Image????
def base64_to_PIL_Image(base64_str):
byte_data = base64.b64decode(base64_str)
image_data = BytesIO(byte_data)
img = Image.open(image_data)
return img
# ???base64_str
def change_img_as_base64(img_name):
with open(img_name, 'rb') as f:
return base64.b64encode(f.read())
# base64_str???
def change_base64_as_img(base64_str, result_img_path=None):
img_data = base64.b64decode(base64_str)
# ????
if result_img_path is not None:
with open(result_img_path, 'wb') as f:
f.write(img_data)
return img_data
# base64_str?opencv??
def change_base64_as_opencv(base64_str):
img_data = base64.b64decode(base64_str)
img_array = np.fromstring(img_data, np.uint8) # ??np??
img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB) # ??Opencv??
return img
In the later work, I will slowly make supplements ......
边栏推荐
- [convolution kernel design] scaling up your kernels to 31x31: revising large kernel design in CNN
- ML10自学笔记-SVM
- 一、PyTorch Cookbook(常用代码合集)
- "Full flash measurement" database acceleration solution
- 【语义分割】Mapillary 数据集简介
- 迁移学习——Transitive Transfer Learning
- 一、迁移学习与fine-tuning有什么区别?
- Anr Optimization: cause oom crash and corresponding solutions
- ML15-神经网络(1)
- 【目标检测】6、SSD
猜你喜欢
[target detection] generalized focal loss v1
【语义分割】Fully Attentional Network for Semantic Segmentation
【DL】关于tensor(张量)的介绍和理解
Continue the new journey and control smart storage together
预训练语言模型的使用方法
How to perform POC in depth with full flash distribution?
clion+opencv+aruco+cmake配置
【Transformer】AdaViT: Adaptive Tokens for Efficient Vision Transformer
【ML】机器学习模型之PMML--概述
第三周周报 ResNet+ResNext
随机推荐
【语义分割】语义分割综述
ML8自学笔记
Technology that deeply understands the principle of MMAP and makes big manufacturers love it
Wechat built-in browser prohibits caching
[DL] introduction and understanding of tensor
Wechat applet source code acquisition (download with tools)
Are you sure you know the interaction problem of activity?
Configuration and use of Nacos external database
【Transformer】SOFT: Softmax-free Transformer with Linear Complexity
Typical cases of xdfs & China Daily Online Collaborative Editing Platform
iSCSI vs iSER vs NVMe-TCP vs NVMe-RDMA
Flink connector Oracle CDC synchronizes data to MySQL in real time (oracle19c)
性能优化之趣谈线程池:线程开的越多就越好吗?
These process knowledge you must know
虚假新闻检测论文阅读(一):Fake News Detection using Semi-Supervised Graph Convolutional Network
二、如何保存MNIST数据集中train和test的图片?
一、multiprocessing.pool.RemoteTraceback
Detailed explanation of MySQL statistical function count
Interesting talk about performance optimization thread pool: is the more threads open, the better?
【Transformer】ACMix:On the Integration of Self-Attention and Convolution