https://blog.youkuaiyun.com/qian1122221/article/details/84567715
https://blog.youkuaiyun.com/wangjian1204/article/details/84445334
环境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)
- numpy array to base64 string
retval, buffer = cv2.imencode('.jpg', pic_img)
pic_str = base64.b64encode(buffer)
pic_str = pic_str.decode()
- 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')
- 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)
OpenCV图像转base64
OpenCV图像的数据类型也是numpy 2维数组,OpenCV提供了cv2.imencode这两个函数来把图片编码成流数据,放到内存缓存中,函数cv2.imdecode可以从编码的数据流恢复到numpy数组:
# OpenCV 图像转base64编码
img = cv2.imread('data/laska.png')
img_str = cv2.imencode('.jpg', img)[1].tostring() # 将图片编码成流数据,放到内存缓存中,然后转化成string格式
b64_code = base64.b64encode(img_str) # 编码成base64
# 从base64编码恢复OpenCV图像
str_decode = base64.b64decode(b64_code)
nparr = np.fromstring(str_decode, np.uint8)
# img_restore = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR) for python 2
img_restore = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
numpy 1维或者2维数组转base64
对于普通的1维或者2维numpy数组,还可以用ByteIO进行编码。
# numpy数组转base64编码
arr = np.arange(12).reshape(3, 4)
bytesio = BytesIO()
np.savetxt(bytesio, arr) # 只支持1维或者2维数组,numpy数组转化成字节流
content = bytesio.getvalue() # 获取string字符串表示
print(content)
b64_code = base64.b64encode(content)
# 从base64编码恢复numpy数组
b64_decode = base64.b64decode(b64_code)
arr = np.loadtxt(BytesIO(b64_decode))
print(arr)
用于HTTP传输的时候通常会用base64.urlsafe_b64encode来代替base64.b64encode,base64.urlsafe_b64decode代替base64.b64decode。两者的区别在于base64.urlsafe_b64encode会把+用-代替,/用_代替,避免URL把+``/当成特殊字符解析了。