import json
import os
from PIL import Image, ImageDraw
def draw_bbox_on_image(image_path, bbox_list, output_path):
image = Image.open(image_path)
draw = ImageDraw.Draw(image)
for bbox in bbox_list:
x, y, w, h = bbox
draw.rectangle([x, y, x + w, y + h], outline="red", width=10)
image.save(output_path)
def process_coco_json(json_file, image_folder, output_folder):
with open(json_file, "r") as f:
data = json.load(f)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
image_id_to_bbox_list = {}
for annotation in data["annotations"]:
image_id = annotation["image_id"]
bbox = annotation["bbox"]
if image_id not in image_id_to_bbox_list:
image_id_to_bbox_list[image_id] = []
image_id_to_bbox_list[image_id].append(bbox)
for image in data["images"]:
image_id = image["id"]
image_path = os.path.join(image_folder, image["file_name"])
output_path = os.path.join(output_folder, image["file_name"])
if image_id in image_id_to_bbox_list:
draw_bbox_on_image(image_path, image_id_to_bbox_list[image_id], output_path)
train_json = "./6354/val_6354.json"# coco标签
train_folder = "./6354/image"# 要使用的绘制图像的文件夹
train_output_folder = "./6354/label_vis" # 输出文件夹
process_coco_json(train_json, train_folder, train_output_folder)