东方耀AI技术分享
标题:
ndarray图片数据与base64字符串之间相互转换
[打印本页]
作者:
东方耀
时间:
2020-5-12 16:24
标题:
ndarray图片数据与base64字符串之间相互转换
ndarray图片数据与base64字符串之间相互转换
import cv2
import base64
import numpy as np
img_path = "./testfiles/face.jpg"
img = cv2.imread(img_path)
print(type(img), img.shape)
ori_h, ori_w, c = img.shape
# ndarray图片数据转base64编码
pic_str = base64.b64encode(img)
print(type(pic_str))
# <class 'bytes'>变成字符串str类型
pic_str = pic_str.decode()
print(type(pic_str))
cv2.imshow("ori", img)
cv2.waitKey(0)
# base64解码 转成ndarray类型
img_data = base64.b64decode(pic_str)
nparr = np.fromstring(img_data, np.uint8)
print(type(nparr), nparr.shape, nparr.dtype)
nparr = nparr.reshape((ori_h, ori_w, c))
print(type(nparr), nparr.shape, nparr.dtype)
# img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
cv2.imshow("ori_64", nparr)
cv2.waitKey(0)
复制代码
base64编码 对字符串的 而不是图像数据本身
# -*- coding: utf-8 -*-
__author__ = u'东方耀 微信:dfy_88888'
__date__ = '2020/5/12 下午2:55'
__product__ = 'PyCharm'
__filename__ = 'dfy_demo03'
import cv2
import base64
import numpy as np
img_path = "./testfiles/face.jpg"
img = cv2.imread(img_path)
print(type(img), img.shape)
# 将图片编码成流数据,放到内存缓存中,然后转化成string格式
img_str = cv2.imencode('.png', img)[1].tostring()
# base64编码 对字符串的 而不是图像数据本身
pic_str = base64.b64encode(img_str)
print(type(pic_str))
# <class 'bytes'>变成字符串str类型
pic_str = pic_str.decode()
print(type(pic_str))
print("字符串的长度:", len(pic_str))
cv2.imshow("ori", img)
cv2.waitKey(0)
# base64解码 转成ndarray类型
img_data = base64.b64decode(pic_str)
nparr = np.fromstring(img_data, np.uint8)
print(type(nparr), nparr.shape, nparr.dtype)
img_restore = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
print(type(img_restore), img_restore.shape, img_restore.dtype)
cv2.imshow("img_restore", img_restore)
cv2.waitKey(0)
复制代码
# 用于HTTP传输的时候通常会用
# base64.urlsafe_b64encode代替base64.b64encode,
# base64.urlsafe_b64decode代替base64.b64decode
#
# 两者的区别在于base64.urlsafe_b64encode会把+用-代替,/用_代替,避免URL把+``/当成特殊字符解析了
# -*- coding: utf-8 -*-
__author__ = u'东方耀 微信:dfy_88888'
__date__ = '2020/5/12 下午2:55'
__product__ = 'PyCharm'
__filename__ = 'dfy_demo03'
import cv2
import base64
import numpy as np
img_path = "./testfiles/face.jpg"
img = cv2.imread(img_path)
print(type(img), img.shape)
# 将图片编码成流数据,放到内存缓存中,然后转化成string格式
img_str = cv2.imencode('.png', img)[1].tostring()
# base64编码 对字符串的 而不是图像数据本身
# pic_str = base64.b64encode(img_str)
pic_str = base64.urlsafe_b64encode(img_str)
print(type(pic_str))
# <class 'bytes'>变成字符串str类型
pic_str = pic_str.decode()
print(type(pic_str))
print("字符串的长度:", len(pic_str))
cv2.imshow("ori", img)
cv2.waitKey(0)
# base64解码 转成ndarray类型
# img_data = base64.b64decode(pic_str)
img_data = base64.urlsafe_b64decode(pic_str)
nparr = np.fromstring(img_data, np.uint8)
print(type(nparr), nparr.shape, nparr.dtype)
img_restore = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
print(type(img_restore), img_restore.shape, img_restore.dtype)
cv2.imshow("img_restore", img_restore)
cv2.waitKey(0)
复制代码
欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/)
Powered by Discuz! X3.4