图像处理——图像与字符串互转

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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值