import json import os import shutil import random from collections import defaultdict # =================配置================= COCO_ROOT = '.' OUT_ROOT = '.' # 输出目录 # 数量配置 NUM_SFT = 100 NUM_GRPO = 200 NUM_TEST = 200 # =================工具函数:坐标转换================= def convert_coco_to_qwen_bbox(coco_bbox, img_width, img_height): """ 将 COCO 格式 [x, y, w, h] 转换为 Qwen-VL 格式 [x1, y1, x2, y2] (归一化到 0-1000) """ x, y, w, h = coco_bbox # 1. 转为左上角 + 右下角 (像素) x1 = x y1 = y x2 = x + w y2 = y + h # 2. 归一化到 0-1000 # 使用 max/min 防止因浮点误差或标注超出边界导致数值越界 norm_x1 = max(0, min(1000, int((x1 / img_width) * 1000))) norm_y1 = max(0, min(1000, int((y1 / img_height) * 1000))) norm_x2 = max(0, min(1000, int((x2 / img_width) * 1000))) norm_y2 = max(0, min(1000, int((y2 / img_height) * 1000))) # 3. 返回格式化列表 [x1, y1, x2, y2] # 注意:这里直接返回整数列表,JSON 序列化后就是 [530,562,576,650] 这种格式 return [norm_x1, norm_y1, norm_x2, norm_y2] # =================1. 中英文映射表 (COCO 80类)================= COCO_CN_MAP = { "person": "人", "bicycle": "自行车", "car": "汽车", "motorcycle": "摩托车", "airplane": "飞机", "bus": "公交车", "train": "火车", "truck": "卡车", "boat": "船", "traffic light": "交通灯", "fire hydrant": "消防栓", "stop sign": "停车标志", "parking meter": "停车计时器", "bench": "长椅", "bird": "鸟", "cat": "猫", "dog": "狗", "horse": "马", "sheep": "羊", "cow": "牛", "elephant": "大象", "bear": "熊", "zebra": "斑马", "giraffe": "长颈鹿", "backpack": "背包", "umbrella": "雨伞", "handbag": "手提包", "tie": "领带", "suitcase": "行李箱", "frisbee": "飞盘", "skis": "滑雪板", "snowboard": "单板滑雪", "sports ball": "运动球", "kite": "风筝", "baseball bat": "棒球棒", "baseball glove": "棒球手套", "skateboard": "滑板", "surfboard": "冲浪板", "tennis racket": "网球拍", "bottle": "瓶子", "wine glass": "酒杯", "cup": "杯子", "fork": "叉子", "knife": "刀", "spoon": "勺子", "bowl": "碗", "banana": "香蕉", "apple": "苹果", "sandwich": "三明治", "orange": "橘子", "broccoli": "西兰花", "carrot": "胡萝卜", "hot dog": "热狗", "pizza": "披萨", "donut": "甜甜圈", "cake": "蛋糕", "chair": "椅子", "couch": "沙发", "potted plant": "盆栽", "bed": "床", "dining table": "餐桌", "toilet": "马桶", "tv": "电视", "laptop": "笔记本电脑", "mouse": "鼠标", "remote": "遥控器", "keyboard": "键盘", "cell phone": "手机", "microwave": "微波炉", "oven": "烤箱", "toaster": "烤面包机", "sink": "水槽", "refrigerator": "冰箱", "book": "书", "clock": "时钟", "vase": "花瓶", "scissors": "剪刀", "teddy bear": "泰迪熊", "hair drier": "吹风机", "toothbrush": "牙刷" } def get_cn_name(en_name): return COCO_CN_MAP.get(en_name, en_name) # =================2. 确定选中的 50 个类别================= def get_selected_ids(): stats = defaultdict(list) cat_map = {} for split in ['train', 'val']: path = os.path.join(COCO_ROOT, 'annotations', f'instances_{split}2017.json') with open(path) as f: data = json.load(f) if split == 'train': cat_map = {c['id']: c['name'] for c in data['categories']} for ann in data['annotations']: w, h = ann['bbox'][2], ann['bbox'][3] stats[ann['category_id']].append(w * h) avg_areas = [(cid, sum(areas)/len(areas)) for cid, areas in stats.items()] avg_areas.sort(key=lambda x: x[1]) selected = [x[0] for x in (avg_areas[:25] + avg_areas[-25:])] return selected, cat_map selected_ids, id_to_en_name = get_selected_ids() id_to_cn_name = {cid: get_cn_name(name) for cid, name in id_to_en_name.items()} print(f"已选定 {len(selected_ids)} 个类别。") output_file = os.path.join(OUT_ROOT, 'selected_categories.json') fine_names = [id_to_cn_name[cid] for cid in selected_ids[:25]] reg_names = [id_to_cn_name[cid] for cid in selected_ids[25:]] result_data = {"fine": fine_names, "reg": reg_names} with open(output_file, 'w', encoding='utf-8') as f: json.dump(result_data, f, ensure_ascii=False, indent=2) # =================3. 加载全量数据索引 (包含图片宽高)================= img_db = defaultdict(list) img_info = {} # img_id -> {file_name, split, width, height} for split in ['train', 'val']: path = os.path.join(COCO_ROOT, 'annotations', f'instances_{split}2017.json') with open(path) as f: data = json.load(f) # 关键修改:保存图片的 width 和 height for img in data['images']: img_info[img['id']] = { 'file_name': img['file_name'], 'split': split, 'width': img['width'], 'height': img['height'] } for ann in data['annotations']: if ann['category_id'] in selected_ids: img_db[ann['image_id']].append(ann) # 按类别构建初始图片池 class_pool = defaultdict(list) for img_id, anns in img_db.items(): cids = set(ann['category_id'] for ann in anns) for cid in cids: class_pool[cid].append(img_id) random.seed(42) # =================4. 流式构建三个数据集================= tasks = [ {'mode': 'data_sft', 'count': NUM_SFT}, {'mode': 'data_grpo', 'count': NUM_GRPO}, {'mode': 'data_test', 'count': NUM_TEST} ] used_images_global = set() for task in tasks: mode = task['mode'] count_per_cat = task['count'] print(f"\n开始构建 {mode} (每类目标: {count_per_cat})...") mode_img_root = os.path.join(OUT_ROOT, mode, 'images') os.makedirs(mode_img_root, exist_ok=True) jsonl_path = os.path.join(OUT_ROOT, mode, 'labels.jsonl') total_count = 0 with open(jsonl_path, 'w', encoding='utf-8') as jf: for cid in selected_ids: cat_name = id_to_cn_name[cid] full_pool = class_pool[cid] available_pool = [img_id for img_id in full_pool if img_id not in used_images_global] num_needed = min(len(available_pool), count_per_cat) if len(available_pool) < count_per_cat and len(available_pool) > 0: print(f" [提示] 类别 '{cat_name}' 剩余可用图片仅 {len(available_pool)} 张。") elif len(available_pool) == 0: print(f" [警告] 类别 '{cat_name}' 无可用图片!") sampled_ids = random.sample(available_pool, num_needed) if num_needed > 0 else [] cat_dir = os.path.join(mode_img_root, cat_name) os.makedirs(cat_dir, exist_ok=True) for img_id in sampled_ids: info = img_info[img_id] fname = info['file_name'] split = info['split'] # 获取图片真实宽高用于转换 w_orig = info['width'] h_orig = info['height'] src = os.path.join(COCO_ROOT, f'{split}2017', fname) dst = os.path.join(cat_dir, fname) if not os.path.exists(dst): shutil.copy2(src, dst) used_images_global.add(img_id) # 【核心修改】构建 objects 时转换 bbox objects = [] for a in img_db[img_id]: # 1. 转换坐标 new_bbox = convert_coco_to_qwen_bbox(a['bbox'], w_orig, h_orig) # 2. 构建对象 objects.append({ "category": id_to_cn_name[a['category_id']], "bbox": new_bbox # 现在是 [x1, y1, x2, y2] (0-1000) }) rel_path = f"images/{cat_name}/{fname}" # 写入 JSONL jf.write(json.dumps({"image": rel_path, "objects": objects}, ensure_ascii=False) + '\n') total_count += 1 print(f" -> {mode} 完成,共生成 {total_count} 张图片。") print("\n================ 全部完成 ================") print(f"输出目录: {OUT_ROOT}")