#coding=utf-8
import json
import os
def convert_labelme_to_yolo(json_file, output_txt_file, label_to_class_id):
with open(json_file, 'r') as file:
data = json.load(file)
image_width = data['imageWidth']
image_height = data['imageHeight']
with open(output_txt_file, 'w') as file:
for shape in data['shapes']:
points = shape['points']
class_id = label_to_class_id.get(shape['label'], -1)
normalized_points = []
for x, y in points:
nx = round(x / image_width, 6)
ny = round(y / image_height, 6)
normalized_points.append(f"{nx} {ny}")
file.write(f"{class_id} " + " ".join(normalized_points) + "\n")
def batch_convert(json_folder, output_folder, label_to_class_id):
# 确保输出文件夹存在
os.makedirs(output_folder, exist_ok=True)
# 遍历文件夹中的所有JSON文件
for filename in os.listdir(json_folder):
if filename.endswith('.json'):
json_file = os.path.join(json_folder, filename)
output_txt_file = os.path.join(output_folder, filename.replace('.json', '.txt'))
convert_labelme_to_yolo(json_file, output_txt_file, label_to_class_id)
def create_label_file(label_dict, output_path):
sorted_labels = [label for label, _ in sorted(label_dict.items(), key=lambda item: item[1])]
with open(output_path, 'w') as file:
for label in sorted_labels:
file.write(f"{label}\n")
if __name__ == '__main__':
# 使用示例
label_to_class_id = {
'road': 0,
'car': 1,
'tree': 2
}
json_folder = './datasets/before'
output_folder = './datasets/before'
batch_convert(json_folder, output_folder, label_to_class_id)
# 生成lableme.txt文件,按照label_dict的值从小到大排列,一个类别1行
create_label_file(label_to_class_id, './datasets/before/yolo-label.txt')
另附分割区域可视化代码:
#coding=utf-8
import base64
import json
import os
import os.path as osp
import numpy as np
import PIL.Image
from labelme import utils
if __name__ == '__main__':
jpgs_path = "datasets/JPEGImages"
pngs_path = "datasets/SegmentationClass"
classes = ["_background_", "car", "tree", "road"]
count = os.listdir("./datasets/before/")
for i in range(0, len(count)):
path = os.path.join("./datasets/before", count[i])
if os.path.isfile(path) and path.endswith('json'):
data = json.load(open(path))
if data['imageData']:
imageData = data['imageData']
else:
imagePath = os.path.join(os.path.dirname(path), data['imagePath'])
with open(imagePath, 'rb') as f:
imageData = f.read()
imageData = base64.b64encode(imageData).decode('utf-8')
img = utils.img_b64_to_arr(imageData)
label_name_to_value = {'_background_': 0}
for shape in data['shapes']:
label_name = shape['label']
if label_name in label_name_to_value:
label_value = label_name_to_value[label_name]
else:
label_value = len(label_name_to_value)
label_name_to_value[label_name] = label_value
# label_values must be dense
label_values, label_names = [], []
for ln, lv in sorted(label_name_to_value.items(), key=lambda x: x[1]):
label_values.append(lv)
label_names.append(ln)
assert label_values == list(range(len(label_values)))
lbl = utils.shapes_to_label(img.shape, data['shapes'], label_name_to_value)
PIL.Image.fromarray(img).save(osp.join(jpgs_path, count[i].split(".")[0] + '.jpg'))
new = np.zeros([np.shape(img)[0], np.shape(img)[1]])
for name in label_names:
index_json = label_names.index(name)
index_all = classes.index(name)
# new = new + index_all * (np.array(lbl) == index_json)
new = new + index_all * (np.array(lbl[0]) == index_json)
utils.lblsave(osp.join(pngs_path, count[i].split(".")[0] + '.png'), new)
print('Saved ' + count[i].split(".")[0] + '.jpg and ' + count[i].split(".")[0] + '.png')