使用python,将文件夹中所有的labelme标注生成的json文件转换为可以用于labelimg标注的yolo格式的yaml文件,且文件名与原文件名一致。
时间: 2024-02-15 11:04:51 浏览: 78
可以使用以下代码实现:
```python
import os
import json
import yaml
# 设置标签类别
classes = ["object"]
# 待转换json文件所在的文件夹
json_folder = "/path/to/json/folder"
# 转换后yaml文件所在的文件夹
yaml_folder = "/path/to/yaml/folder"
# 遍历json文件
for filename in os.listdir(json_folder):
if filename.endswith(".json"):
with open(os.path.join(json_folder, filename), "r") as f:
data = json.load(f)
img_width = data["imageWidth"]
img_height = data["imageHeight"]
objects = []
for shape in data["shapes"]:
label = shape["label"]
points = shape["points"]
xmin = min([point[0] for point in points])
ymin = min([point[1] for point in points])
xmax = max([point[0] for point in points])
ymax = max([point[1] for point in points])
object_dict = {"name": label, "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax}
objects.append(object_dict)
# 写入yaml文件
yaml_filename = os.path.splitext(filename)[0] + ".yaml"
with open(os.path.join(yaml_folder, yaml_filename), "w") as f:
yaml_dict = {"image": os.path.splitext(filename)[0] + ".jpg", "width": img_width, "height": img_height, "depth": 3, "objects": objects, "classes": classes}
yaml.dump(yaml_dict, f)
# 写入txt文件
txt_filename = os.path.splitext(filename)[0] + ".txt"
with open(os.path.join(yaml_folder, txt_filename), "w") as f:
for obj in objects:
class_index = classes.index(obj["name"])
x_center = (obj["xmin"] + obj["xmax"]) / 2 / img_width
y_center = (obj["ymin"] + obj["ymax"]) / 2 / img_height
width = (obj["xmax"] - obj["xmin"]) / img_width
height = (obj["ymax"] - obj["ymin"]) / img_height
txt_line = "{} {:.6f} {:.6f} {:.6f} {:.6f}\n".format(class_index, x_center, y_center, width, height)
f.write(txt_line)
```
这段代码会遍历指定文件夹中所有的json文件,将每个文件中的标注信息转换为yolo格式的yaml文件和txt文件。其中,yaml文件用于在labelimg中显示标注信息,txt文件用于训练yolo模型。在此代码中,我们将标签类别统一设置为"object",如果需要添加其他类别,可以修改`classes`列表。同时,这段代码会保持新文件与原文件名相同。
阅读全文