json格式,比如提取轮廓,不想手动打图像分割标签的可以用这个方法。
from labelme import PY2
from labelme import QT4
from labelme.logger import logger
import base64
import io
import numpy as np
from PIL import ExifTags
# import PIL.ExifTags
from PIL import Image
# import PIL.Image
# import PIL.ImageOps
from PIL import ImageOps
import os
import os.path as osp
import json
class MyEncoder(json.JSONEncoder):
def default(self, obj):
"""
只要检查到了是bytes类型的数据就把它转为str类型
:param obj:
:return:
"""
if isinstance(obj, bytes):
return str(obj, encoding='utf-8')
return json.JSONEncoder.default(self, obj)
def apply_exif_orientation(image):
try:
exif = image._getexif()
except AttributeError:
exif = None
if exif is None:
return image
exif = {
ExifTags.TAGS[k]: v
for k, v in exif.items()
if k in ExifTags.TAGS
}
orientation = exif.get('Orientation', None)
if orientation == 1:
# do nothing
return image
elif orientation == 2:
# left-to-right mirror
return ImageOps.mirror(image)
elif orientation == 3:
# rotate 180
return image.transpose(Image.ROTATE_180)
elif orientation == 4:
# top-to-bottom mirror
return ImageOps.flip(image)
elif orientation == 5:
# top-to-left mirror
return ImageOps.mirror(image.transpose(Image.ROTATE_270))
elif orientation == 6:
# rotate 270
return image.transpose(Image.ROTATE_270)
elif orientation == 7:
# top-to-right mirror
return ImageOps.mirror(image.transpose(Image.ROTATE_90))
elif orientation == 8:
# rotate 90
return image.transpose(Image.ROTATE_90)
else:
return image
#@staticmethod
def load_image_file(filename):
try:
image_pil = Image.open(filename)
except IOError:
logger.error('Failed opening image file: {}'.format(filename))
return
# apply orientation to image according to exif
image_pil = apply_exif_orientation(image_pil)
with io.BytesIO() as f:
ext = osp.splitext(filename)[1].lower()
if PY2 and QT4:
format = 'PNG'
elif ext in ['.jpg', '.jpeg']:
format = 'JPEG'
else:
format = 'PNG'
image_pil.save(f, format=format)
f.seek(0)
return f.read()
data = {}
path = './'
imageList=os.listdir(path)
print(imageList)
for imageName in imageList:
if imageName.endswith('.jpg'):
imageData = load_image_file(osp.join(path,imageName))
imageData=base64.b64encode(imageData).decode('utf-8') #此时imageData是unicode格式,需要转成str
str1 = imageData.encode('gbk')
print(str1)
data["imageData"] = str1
with open('./1.json', 'w') as wf:
json.dump(data, wf,cls=MyEncoder,indent=4)