contrast_method / grounding-dino /data_precess_train.py
qq-2's picture
Add files using upload-large-folder tool
2bb358d verified
import json
import os
import cv2
from pathlib import Path
# ================= 配置区域 =================
BASE_DIR = Path(__file__).resolve().parent
WORKSPACE_DIR = BASE_DIR.parent.parent
jsonl_file = str(WORKSPACE_DIR / 'rex_data' / 'data' / 'rex-omni-data' / 'train' / 'merged_shuffled_no_rect_from_wuhan_plus_replenish_mixed_vis_temp_empty_gt.jsonl') # 你的原始数据路径
output_dir = str(BASE_DIR / 'dataset') # 输出文件夹名
json_name = 'train_traffic_data_2_25.json' # 输出的 json 文件名
# 统一图片根目录:新文件里有多个子目录(如 PanoImages_data_all / crops_scaled1p5 / crop_empty)
img_root = str(WORKSPACE_DIR / 'rex_data' / 'data')
# 当图片不在 img_root 下时,是否允许在 COCO 的 file_name 里写绝对路径
allow_absolute_file_name = True
# 类别映射 (MMDet 中 ID 建议从 1 开始,或者保持 0,CocoDataset默认兼容)
# 这里的顺序非常重要,必须和后面 Config 里的 class_name 顺序一致
categories = [
{"id": 0, "name": "traffic sign"},
{"id": 1, "name": "street light"},
{"id": 2, "name": "traffic light"},
{"id": 3, "name": "surveillance camera"},
{"id": 4, "name": "ball bollard"},
{"id": 5, "name": "fire hydrant"},
{"id": 6, "name": "trash bin"},
{"id": 7, "name": "manhole"},
{"id": 8, "name": "traffic cone"},
{"id": 9, "name": "bollard"}
]
# ===========================================
def resolve_image_path(raw_path):
"""支持绝对路径和相对路径(相对 jsonl 或相对 img_root)。"""
if not raw_path:
return None
raw_path = os.path.expanduser(str(raw_path))
if os.path.isabs(raw_path):
return raw_path
candidates = [
os.path.join(os.path.dirname(jsonl_file), raw_path),
os.path.join(img_root, raw_path)
]
for p in candidates:
if os.path.exists(p):
return os.path.abspath(p)
return os.path.abspath(candidates[0])
def build_file_name(img_path):
"""优先写相对 img_root 的路径;不在 img_root 下时可回退到绝对路径。"""
rel_path = os.path.relpath(img_path, img_root)
if not rel_path.startswith('..'):
return rel_path.replace('\\', '/')
if allow_absolute_file_name:
return os.path.abspath(img_path).replace('\\', '/')
return None
def main():
os.makedirs(output_dir, exist_ok=True)
dst_img_dir = os.path.join(output_dir, 'images')
os.makedirs(dst_img_dir, exist_ok=True)
images = []
annotations = []
# 建立名字到ID的映射
cat_map = {cat['name']: cat['id'] for cat in categories}
print(f"Reading {jsonl_file}...")
data_lines = []
with open(jsonl_file, 'r', encoding='utf-8') as f:
for line in f:
if line.strip():
data_lines.append(json.loads(line))
print(f"Converting {len(data_lines)} images to COCO format...")
ann_id = 0
img_id = 0
for entry in data_lines:
raw_img_path = entry.get('image_name') or entry.get('image_path')
img_path = resolve_image_path(raw_img_path)
if not img_path:
continue
# 1. 检查并读取图片 (需要宽高)
if not os.path.exists(img_path):
print(f"Skip: {img_path} not found")
continue
img = cv2.imread(img_path)
if img is None: continue
h, w = img.shape[:2]
file_name = build_file_name(img_path)
if file_name is None:
print(f"Skip: {img_path} is outside img_root={img_root}")
continue
# 2. 这里的策略是:不复制图片,直接用软链接,或者在 config 里指定原图路径
# 为了方便,这里我们假设你不想复制几千张图,所以只生成 JSON
# Config 里的 data_prefix 需要指向原图所在的【父目录】
images.append({
"id": img_id,
"file_name": file_name, # 存相对 img_root 的路径,避免同名文件冲突
"height": h,
"width": w
})
# 3. 处理标注
boxes = entry.get('annotation', {}).get('boxes', [])
for box_item in boxes:
phrase = box_item.get('phrase')
bbox = box_item.get('bbox') # [x1, y1, x2, y2]
if phrase not in cat_map:
continue
cat_id = cat_map[phrase]
if not isinstance(bbox, (list, tuple)) or len(bbox) != 4:
continue
# 坐标转换: xyxy -> xywh
x1, y1, x2, y2 = map(float, bbox)
coco_w = x2 - x1
coco_h = y2 - y1
if coco_w <= 0 or coco_h <= 0:
continue
annotations.append({
"id": ann_id,
"image_id": img_id,
"category_id": cat_id,
"bbox": [x1, y1, coco_w, coco_h],
"area": coco_w * coco_h,
"iscrowd": 0
})
ann_id += 1
img_id += 1
# 简单打印进度
if img_id % 500 == 0:
print(f"Processed {img_id}...")
# 构建最终字典
coco_output = {
"images": images,
"annotations": annotations,
"categories": categories
}
save_path = os.path.join(output_dir, json_name)
with open(save_path, 'w') as f:
json.dump(coco_output, f)
print(f"Done! Saved to {save_path}")
print(f"Total Images: {len(images)}, Total Annotations: {len(annotations)}")
if __name__ == "__main__":
main()