gpcv_incontext_bench / convert_jsonl.py
insomnia7's picture
Add files using upload-large-folder tool
2c986a2 verified
Raw
History Blame Contribute Delete
4.52 kB
import os
import json
from PIL import Image
from pathlib import Path
def yolo_to_xyxy(bbox, img_width, img_height):
"""
将 YOLO 格式 (center_x, center_y, width, height) 转换为 xyxy 格式
坐标是归一化的,需要转换为绝对坐标
"""
center_x, center_y, width, height = bbox
x1 = (center_x - width / 2) * img_width
y1 = (center_y - height / 2) * img_height
x2 = (center_x + width / 2) * img_width
y2 = (center_y + height / 2) * img_height
return [int(x1), int(y1), int(x2), int(y2)]
def process_folder(category_path, category_name, output_file):
"""
处理单个类别文件夹
"""
images_dir = category_path / "images"
labels_dir = category_path / "labels_yolo"
if not images_dir.exists() or not labels_dir.exists():
print(f"警告: {category_path} 中缺少 images 或 labels_yolo 文件夹")
return 0, 0
# 获取所有图片文件(支持更多格式)
image_files = []
for ext in ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.tif', '*.tiff', '*.JPG', '*.PNG', '*.TIF', '*.TIFF']:
image_files.extend(images_dir.glob(ext))
processed_count = 0
total_bboxes = 0
for img_path in image_files:
# 获取对应的标签文件
label_file = labels_dir / f"{img_path.stem}.txt"
if not label_file.exists():
continue
# 获取图片尺寸
try:
with Image.open(img_path) as img:
img_width, img_height = img.size
except Exception as e:
print(f"错误: 无法读取图片 {img_path}, {e}")
continue
# 读取标签文件
bboxes = []
with open(label_file, 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
parts = line.split()
if len(parts) != 5:
continue
class_id = int(parts[0])
center_x = float(parts[1])
center_y = float(parts[2])
width = float(parts[3])
height = float(parts[4])
# 转换为 xyxy 格式
xyxy = yolo_to_xyxy([center_x, center_y, width, height], img_width, img_height)
bboxes.append({
"bbox": xyxy, # [x1, y1, x2, y2]
"category": category_name,
"class_id": class_id
})
# 构造 JSONL 行
json_line = {
"image": str(img_path.absolute()),
"image_path": str(img_path),
"width": img_width,
"height": img_height,
"bboxes": bboxes
}
# 写入输出文件
output_file.write(json.dumps(json_line, ensure_ascii=False) + '\n')
processed_count += 1
total_bboxes += len(bboxes)
return processed_count, total_bboxes
def main():
# 当前目录
base_dir = Path("/home/disk2/hjl/ICL_QWEN/ICL_benchmark")
# 需要处理的文件夹(排除 dinov3 开头的)
exclude_prefixes = ["dinov3"]
# 输出文件
output_path = base_dir / "dataset.jsonl"
total_images = 0
total_bboxes_all = 0
with open(output_path, 'w', encoding='utf-8') as outfile:
# 遍历所有文件夹
for item in base_dir.iterdir():
if not item.is_dir():
continue
# 检查是否需要排除
should_exclude = False
for prefix in exclude_prefixes:
if item.name.startswith(prefix):
should_exclude = True
break
if should_exclude:
print(f"跳过文件夹: {item.name}")
continue
# 处理该类别文件夹
print(f"处理类别: {item.name}", end=' ', flush=True)
processed, bboxes = process_folder(item, item.name, outfile)
print(f"完成 - 处理了 {processed} 张图片, {bboxes} 个标注")
total_images += processed
total_bboxes_all += bboxes
print(f"\n{'='*50}")
print(f"转换完成!")
print(f"总图片数: {total_images}")
print(f"总标注数: {total_bboxes_all}")
print(f"输出文件: {output_path}")
if __name__ == "__main__":
main()