目标检测绘制json到图像上
【代码】目标检测绘制json到图像上。
·
import argparse
import cv2
import json
def draw_boxes(image_path, json_path, output_path):
# 读取JSON文件
with open(json_path, 'r') as f:
data = json.load(f)
# 读取图像路径
image = cv2.imread(image_path)
# 绘制框
for annotation in data['annotations']:
bbox = annotation['bbox']
x, y, width, height = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
cv2.rectangle(image, (x, y), (x + width, y + height), (0, 255, 0), 2)
category_id = annotation['category_id']
category_name = [category['name'] for category in data['categories'] if category['id'] == category_id][0]
cv2.putText(image, category_name, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# 保存绘制后的图片
cv2.imwrite(output_path, image)
if __name__ == "__main__":
# 解析命令行参数
parser = argparse.ArgumentParser(description="Draw bounding boxes on an image based on annotations in a JSON file")
parser.add_argument("--img_path", help="Path to the image file", required=True)
parser.add_argument("--json_path", help="Path to the JSON file containing annotations", required=True)
parser.add_argument("--output_path", help="Path to save the output image", required=True)
args = parser.parse_args()
# 调用绘制函数并保存结果
draw_boxes(args.img_path, args.json_path, args.output_path)
更多推荐
所有评论(0)