1、图像转字符串
from sys import argv
from base64 import b64encode
from json import dumps
# 命令行窗口执行python image_to_json.py result.png result.json
ENCODING = 'utf-8' # 指定编码形式
SCRIPT_NAME, IMAGE_NAME, JSON_NAME = argv # 获得文件名参数
# 读取二进制图片,获得原始字节码,注意 'rb'
with open(IMAGE_NAME, 'rb') as jpg_file:
byte_content = jpg_file.read()
# 把原始字节码编码成 base64 字节码
base64_bytes = b64encode(byte_content)
# 将 base64 字节码解码成 utf-8 格式的字符串
base64_string = base64_bytes.decode(ENCODING)
# 用字典的形式保存数据
raw_data = {}
raw_data["name"] = IMAGE_NAME
raw_data["image_base64_string"] = base64_string
# 将字典变成 json 格式,缩进为 2 个空格
json_data = dumps(raw_data, indent=2)
# 将 json 格式的数据保存到文件中
with open(JSON_NAME, 'w') as json_file:
json_file.write(json_data)
json文件内容如下:
{
"name": "result.png",
"image_base64_string":"iVBORw0KGgoAAAANSUhEUgAABEAAAAGOCAIAAAAYR...",
}
2、字符串转图像
from sys import argv
import base64
import json
# 命令行窗口执行python json_to_image.py result.json result_new.png
# 从命令行获得文件名参数
SCRIPT_NAME, JSON_NAME, IMAGE_NAME = argv
# 读取 json 文件,并直接存入字典
with open(JSON_NAME, "r") as json_file:
raw_data = json.load(json_file)
# 从字典中取得图片的 base64 字符串
image_base64_string = raw_data["image_base64_string"]
# 将 base64 字符串解码成图片字节码
image_data = base64.b64decode(image_base64_string)
# 将字节码以二进制形式存入图片文件中,注意 'wb'
with open(IMAGE_NAME, 'wb') as jpg_file:
jpg_file.write(image_data)
将labelme生成的json文件转成原始图像和mask图像,代码如下:
labelme_json_to_dataset -o files files\label.json