图像base64与numpy array之间的转换

3 篇文章 0 订阅
2 篇文章 0 订阅

环境python3.6

import base64
import cv2
import numpy as np

1.base64 string to numpy array

image_string = request_data['image']
img_data = base64.b64decode(image_string)
nparr = np.fromstring(img_data, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

2. numpy array to base64 string

retval, buffer = cv2.imencode('.jpg', pic_img)
pic_str = base64.b64encode(buffer)
pic_str = pic_str.decode()

3. image file to base64 directly

with open(img_path, "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read())
    req_file = encoded_image.decode('utf-8')

4. post request using the base64 string as part of json parameters

import requests
import json
with open(img_path, "rb") as image_file:
    encoded_image = base64.b64encode(image_file.read())
    req_file = encoded_image.decode('utf-8')
#json format parameters
post_dict = {"image": req_file, "type": 0}
headers = {
    'Content-Type': 'application/json',  # This is important
}
response = requests.post(url, data=json.dumps(post_dict), headers=headers)

#the host using jsonify(from flask) to return the result
result = json.loads(response.content.decode('utf8'))
pic_str = result['data']['pic_str']
pic_str = pic_str.encode('utf-8')
jpg_original = base64.b64decode(pic_str)
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
image_buffer = cv2.imdecode(jpg_as_np, flags=1)
cv2.imshow("asd", image_buffer)
cv2.waitKey(0)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值