python调试
import json
import numpy as np
from cv2 import cv2
import labelme.utils as lu
import PIL.ExifTags
import PIL.Image
import PIL.ImageOps
import base64
img_path = ''
def img_arr_to_b64(img_arr):
img_pil = PIL.Image.fromarray(img_arr)
f = io.BytesIO()
# img_pil.save(f, format="PNG")
img_pil.save(f, format="JPEG")
img_bin = f.getvalue()
if hasattr(base64, "encodebytes"):
img_b64 = base64.encodebytes(img_bin)
else:
img_b64 = base64.encodestring(img_bin)
# imagedata=str(base64.b64encode(img_bin), 'utf-8')
imagedata=str(base64.b64encode(img_bin).decode("utf-8"))
return imagedata
img_pil = PIL.Image.open(img_path)
img_arr = np.array(img_pil)
# img_arr = img_data_to_arr(img)
img_b64 = img_arr_to_b64(img_arr)
在调试程序中发现选择img_pil.save(f, format="JPEG")
的参数format
为JPEG
时解析的结果和labelme可视化的Qt界面保存的结果比较相似。
js实现
在前端vue中可使用以下方法得到base64编码,参数fileObj
为传入图像file
的file.raw
:
getBase64Image(fileObj) {
return new Promise(function(resolve) {
const image = new Image()
image.src = URL.createObjectURL(fileObj)
image.onload = function() {
const that = this;
var canvas = document.createElement("canvas");
canvas.width = that.width;
canvas.height = that.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(that, 0, 0, canvas.width, canvas.height);
var dataURL = canvas.toDataURL("image/jpeg", 0.75);
// 注意该压缩率参数,可调节,但本人觉得0.75差不多
resolve(dataURL);
}
});
},
注意得到的base64编码带有前缀,labelme生成的json的imageData
项则没有,可以把去掉前缀的编码复制到json中尝试用labelme打开以检验。