labelme 保存 imageData 机制探究


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")的参数formatJPEG时解析的结果和labelme可视化的Qt界面保存的结果比较相似。

js实现

在前端vue中可使用以下方法得到base64编码,参数fileObj为传入图像filefile.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打开以检验。

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐