检测bounfingbox脚本,支持多文件夹。 bbox格式是x1,y1,x2,y2的
import cv2
import os
import json
def display_bounding_boxes(img_path, bounding_boxes):
# 读取图片
img = cv2.imread(img_path)
# 为每一个bounding box 画框
colors = {
'Bodybox': (0, 0, 255), # 红色
'Facebox': (0, 255, 0), # 绿色
'L_handbox': (255, 0, 0), # 蓝色
'R_handbox': (0, 255, 255) # 黄色
}
for box_name, coords in bounding_boxes.items():
if box_name in colors and coords: # 检查bounding box是否存在并且不是空的
color = colors[box_name]
x1, y1, x2, y2 = coords
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), color, 1)
cv2.putText(img, box_name, (int(x1), int(y1)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
# 在左上角显示路径
cv2.putText(img, img_path, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
# 显示图片
cv2.imshow('Bounding Boxes', img)
def process_json_file(json_path):
with open(json_path, 'r') as f:
data = json.load(f)
if "instances" in data and len(data["instances"]) > 0 and "boundingbox" in data["instances"][0]:
bounding_boxes = data["instances"][0]["boundingbox"]
img_path = data["img_path"]
display_bounding_boxes(img_path, bounding_boxes)
else:
print(f"{json_path} 中的JSON结构存在问题。跳过此文件。")
return
data_folder = " "#box标签路径
categories = [" "]# 文件夹名,可多个
json_files = []
for i in range(1, x): # 有多少文件夹x写几
for category in categories:
folder_path = os.path.join(data_folder, str(i), category)
for filename in os.listdir(folder_path):
if filename.endswith(".json"):
json_files.append(os.path.join(folder_path, filename))
idx = 0
process_json_file(json_files[idx])
while True:
key = cv2.waitKey(0) & 0xFF
if key == 27: # ESC
break
elif key == 52: # 小键盘4,上一页
if idx > 0:
idx -= 1
process_json_file(json_files[idx])
elif key == 54: # 小键盘6,下一页
if idx < len(json_files) - 1:
idx += 1
process_json_file(json_files[idx])
cv2.destroyAllWindows()