当前位置:网站首页>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 ......
边栏推荐
- 【语义分割】Fully Attentional Network for Semantic Segmentation
- 【目标检测】6、SSD
- [DL] build convolutional neural network for regression prediction (detailed tutorial of data + code)
- NLP领域的AM模型
- 一、multiprocessing.pool.RemoteTraceback
- [clustmaps] visitor statistics
- PyTorch中的模型构建
- 三、如何读取视频?
- 一、常见损失函数的用法
- How to perform POC in depth with full flash distribution?
猜你喜欢

【语义分割】Mapillary 数据集简介
![[clustmaps] visitor statistics](/img/1a/173664a633fd14ea56696dd824acb6.png)
[clustmaps] visitor statistics

研究生新生培训第二周:卷积神经网络基础

ML8自学笔记

【目标检测】Generalized Focal Loss V1

Configuration and use of Nacos external database

【语义分割】Fully Attentional Network for Semantic Segmentation

FFmpeg创作GIF表情包教程来了!赶紧说声多谢乌蝇哥?
![[overview] image classification network](/img/2b/7e3ba36a4d7e95cb262eebaadee2f3.png)
[overview] image classification network

【Transformer】ACMix:On the Integration of Self-Attention and Convolution
随机推荐
Change! Change! Change!
ML8自学笔记
【Transformer】SOFT: Softmax-free Transformer with Linear Complexity
Interesting talk about performance optimization thread pool: is the more threads open, the better?
【Transformer】ATS: Adaptive Token Sampling For Efficient Vision Transformers
迁移学习——Robust Visual Domain Adaptation with Low-Rank Reconstruction
Wechat applet source code acquisition (download with tools)
Continue the new journey and control smart storage together
研究生新生培训第三周:ResNet+ResNeXt
[competition website] collect machine learning / deep learning competition website (continuously updated)
【语义分割】Mapillary 数据集简介
【Transformer】TransMix: Attend to Mix for Vision Transformers
Ffmpeg creation GIF expression pack tutorial is coming! Say thank you, brother black fly?
Personal learning website
"Full flash measurement" database acceleration solution
第三周周报 ResNet+ResNext
【图像分类】如何使用 mmclassification 训练自己的分类模型
ML11-SKlearn实现支持向量机
GA-RPN:引导锚点的建议区域网络
虚假新闻检测论文阅读(二):Semi-Supervised Learning and Graph Neural Networks for Fake News Detection