import os
import json
import cv2
def coco_to_yolo_bbox(coco_bbox, img_width, img_height):
x1, y1, x2, y2 = coco_bbox
x_center = (x1 + x2) / 2.0
y_center = (y1 + y2) / 2.0
width = x2 - x1
height = y2 - y1
# 归一化
x_center /= img_width
y_center /= img_height
width /= img_width
height /= img_height
return [x_center, y_center, width, height]
json_folder = ""
img_folder = ""
output_folder = ""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
json_files = [os.path.join(json_folder, f) for f in os.listdir(json_folder) if f.endswith(".json")]
for json_file in json_files:
with open(json_file, 'r') as f:
data = json.load(f)
bbox = data.get("bbox", [])
img_path = os.path.join(img_folder, os.path.splitext(os.path.basename(json_file))[0] + ".jpg")
img = cv2.imread(img_path)
img_height, img_width = img.shape[:2]
yolo_bbox = coco_to_yolo_bbox(bbox, img_width, img_height)
yolo_format = f"2 {' '.join(map(str, yolo_bbox))}\n"
output_file_path = os.path.join(output_folder, os.path.splitext(os.path.basename(json_file))[0] + ".txt")
with open(output_file_path, 'w') as f:
f.write(yolo_format)
这段代码的功能是将 COCO 格式的边界框转换为 YOLO 格式的边界框,并将其保存为 txt 文件。首先,代码定义了一个名为 coco_to_yolo_bbox
的函数,用于将 COCO 格式的边界框转换为 YOLO 格式的边界框。其中,coco_bbox
表示 COCO 格式的边界框列表,img_width
和 img_height
分别表示图像的宽度和高度。函数计算出 YOLO 格式的边界框后,将其以列表形式返回。然后,代码定义了三个变量,分别是 JSON 文件夹路径、图像文件夹路径和输出文件夹路径,并检查输出文件夹是否存在。接下来,代码生成 JSON 文件夹中所有以 .json
结尾的文件的文件路径,并循环遍历每个 JSON 文件。在循环中,代码使用 json.load()
函数读取 JSON 文件中的数据,并提取边界框信息。然后,代码根据图像文件路径读取图像,并获取其宽度和高度。接着,代码调用 coco_to_yolo_bbox()
函数将 COCO 格式的边界框转换为 YOLO 格式的边界框,并将其格式化为 YOLO 格式的字符串。最后,代码将 YOLO 格式的字符串保存为 .txt
文件,文件名与对应的图像文件名相同,只是扩展名不同。总的来说,这段代码主要是用于 COCO 格式与 YOLO 格式边界框格式之间的转换,并将转换后的结果保存为 .txt
文件。