File size: 8,783 Bytes
eaf378c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | 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}") |