File size: 16,542 Bytes
bcb5616 |
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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
import json
import os
from pathlib import Path
import datasets
from PIL import Image
import jsonlines
logger = datasets.logging.get_logger(__name__)
_CITATION = """\
@misc{chen2024paligemma,
title={PaliGemma Multitask Dataset},
author={Chen, Xingqiang},
year={2024},
publisher={Hugging Face}
}
"""
_DESCRIPTION = """\
This dataset contains images and annotations for defect detection and analysis,
designed for training and evaluating the PaliGemma multitask model.
The dataset includes both basic defect detection samples and a larger set of
874 annotated images from real-world structural inspections.
"""
_HOMEPAGE = "https://huggingface.co/datasets/xingqiang/paligemma-multitask-dataset"
class PaligemmaDataset(datasets.GeneratorBasedBuilder):
"""PaliGemma Multitask Dataset for defect detection and analysis."""
VERSION = datasets.Version("1.1.0")
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features({
"image": datasets.Image(),
"boxes": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), length=4)),
"labels": datasets.Sequence(datasets.ClassLabel(names=["void", "crack"])),
"caption": datasets.Value("string"),
"source": datasets.Value("string"),
}),
supervised_keys=None,
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"split": "val",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"split": "test",
},
),
]
def _generate_examples(self, split):
"""生成示例。"""
# 优先加载统一格式的注释
unified_path = os.path.join("annotations", f"{split}_unified.json")
if os.path.exists(unified_path):
logger.info(f"使用统一格式的注释文件: {unified_path}")
with open(unified_path, encoding="utf-8") as f:
annotations = json.load(f)
for idx, ann in enumerate(annotations):
image_path = os.path.join("images", split, ann["image_filename"])
try:
yield f"unified_{idx}", {
"image": image_path,
"boxes": ann["boxes"],
"labels": ann["labels"],
"caption": ann["caption"],
"source": ann.get("source", "unified")
}
except Exception as e:
logger.warning(f"跳过无效图像 {image_path}: {e}")
continue
return # 如果使用了统一格式,不再处理其他格式
# 如果没有统一格式,则回退到原始格式
# 加载原始 JSON 注释
json_path = os.path.join("annotations", f"{split}.json")
if os.path.exists(json_path):
with open(json_path, encoding="utf-8") as f:
annotations = json.load(f)
for idx, ann in enumerate(annotations):
image_path = os.path.join("images", split, ann["image_filename"])
try:
# 不要尝试在这里打开图像,只返回路径
yield f"orig_{idx}", {
"image": image_path,
"boxes": ann["boxes"],
"labels": ann["labels"],
"caption": ann["caption"],
"source": "original"
}
except Exception as e:
logger.warning(f"跳过无效图像 {image_path}: {e}")
continue
# 加载 JSONL 注释
jsonl_path = os.path.join("annotations", f"_annotations.{split}.jsonl")
if os.path.exists(jsonl_path):
with jsonlines.open(jsonl_path) as reader:
for idx, ann in enumerate(reader):
# 确保使用正确的图像文件名
image_filename = ann.get("image", "")
image_path = os.path.join("images", split, image_filename)
try:
# 不要尝试在这里打开图像,只返回路径
# 转换注释为我们的格式
if "annotations" in ann:
# 处理新格式
boxes = [[b["x"], b["y"], b["width"], b["height"]] for b in ann["annotations"]]
labels = [0 if b["class"] == "void" else 1 for b in ann["annotations"]]
caption = f"Image contains {len(boxes)} defects: " + \
", ".join([b["class"] for b in ann["annotations"]])
else:
# 处理旧格式 (prefix/suffix)
# 这里需要解析 suffix 中的位置信息
boxes = []
labels = []
if "suffix" in ann:
parts = ann["suffix"].split(";")
for part in parts:
part = part.strip()
if "<loc" in part:
# 解析位置和标签
loc_parts = part.split()
if len(loc_parts) >= 2:
# 提取坐标
coords = []
for loc in loc_parts[0].split("><"):
if loc.startswith("<loc"):
coords.append(int(loc[4:-1]) / 1024) # 归一化坐标
if len(coords) == 4:
boxes.append(coords)
label = 0 if "void" in loc_parts[1] else 1
labels.append(label)
caption = ann.get("prefix", "")
# 检查图像是否存在
image_exists = False
# 检查images/datasets目录
if os.path.exists(f"images/datasets/{image_filename}"):
image_exists = True
# 检查原始路径
if not image_exists:
for img_split in ["train", "val", "test"]:
if os.path.exists(f"images/{img_split}/{image_filename}"):
image_exists = True
break
if not image_exists:
print(f"警告: 图像文件不存在: {image_filename}")
continue
yield f"p1v1_{idx}", {
"image": image_path,
"boxes": boxes,
"labels": labels,
"caption": caption,
"source": "p1v1"
}
except Exception as e:
logger.warning(f"跳过无效注释 {image_path}: {e}")
continue
def convert_annotations_to_unified_format():
"""将所有注释转换为统一格式"""
print("开始转换注释为统一格式...")
# 确保annotations目录存在
os.makedirs("annotations", exist_ok=True)
# 增加对valid分割的处理(有些文件使用valid而不是val)
for split in ["train", "val", "valid", "test"]:
print(f"处理 {split} 分割...")
unified_annotations = []
# 处理 JSON 注释
json_path = f"annotations/{split}.json"
print(f"检查 JSON 文件: {json_path}")
if os.path.exists(json_path):
print(f"找到 JSON 文件: {json_path}")
with open(json_path, encoding="utf-8") as f:
try:
annotations = json.load(f)
print(f"从 {json_path} 加载了 {len(annotations)} 条注释")
for ann in annotations:
unified_annotations.append({
"image_filename": ann["image_filename"],
"boxes": ann["boxes"],
"labels": ann["labels"],
"caption": ann["caption"],
"source": "original"
})
except json.JSONDecodeError:
print(f"错误: {json_path} 不是有效的 JSON 文件")
else:
print(f"未找到 JSON 文件: {json_path}")
# 处理 JSONL 注释,包括目录p-1.v1i.paligemma下的文件
jsonl_variants = [
f"_annotations.{split}.jsonl",
f"_annotations.{split}1.jsonl",
f"p-1.v1i.paligemma/_annotations.{split}.jsonl",
f"p-1.v1i.paligemma/_annotations.{split}1.jsonl"
]
for jsonl_variant in jsonl_variants:
jsonl_path = f"annotations/{jsonl_variant}"
print(f"检查 JSONL 文件: {jsonl_path}")
if os.path.exists(jsonl_path):
print(f"找到 JSONL 文件: {jsonl_path}")
annotation_count = 0
with open(jsonl_path, encoding="utf-8") as f:
for line_num, line in enumerate(f, 1):
try:
line = line.strip()
if not line: # 跳过空行
print(f"跳过第 {line_num} 行: 空行")
continue
ann = json.loads(line)
image_filename = ann.get("image", "")
if not image_filename:
print(f"跳过第 {line_num} 行: 没有图像文件名")
continue
# 检查图像是否存在
image_exists = False
# 检查images/datasets目录
if os.path.exists(f"images/datasets/{image_filename}"):
image_exists = True
# 检查原始路径
if not image_exists:
for img_split in ["train", "val", "test"]:
if os.path.exists(f"images/{img_split}/{image_filename}"):
image_exists = True
break
if not image_exists:
print(f"警告: 图像文件不存在: {image_filename}")
continue
# 转换为统一格式
if "annotations" in ann:
# 处理新格式
boxes = [[b["x"], b["y"], b["width"], b["height"]] for b in ann["annotations"]]
labels = [0 if b["class"] == "void" else 1 for b in ann["annotations"]]
caption = f"Image contains {len(boxes)} defects: " + \
", ".join([b["class"] for b in ann["annotations"]])
else:
# 处理旧格式 (prefix/suffix)
boxes = []
labels = []
caption = ann.get("prefix", "")
if "suffix" in ann:
parts = ann["suffix"].split(";")
for part in parts:
part = part.strip()
if "<loc" in part:
# 解析位置和标签
loc_parts = part.split()
if len(loc_parts) >= 2:
# 提取坐标
coords = []
for loc in loc_parts[0].split("><"):
if loc.startswith("<loc"):
try:
coords.append(int(loc[4:-1]) / 1024) # 归一化坐标
except ValueError:
continue
if len(coords) == 4:
boxes.append(coords)
label = 0 if "void" in loc_parts[1] else 1
labels.append(label)
unified_annotations.append({
"image_filename": image_filename,
"boxes": boxes,
"labels": labels,
"caption": caption,
"source": "p1v1"
})
annotation_count += 1
except json.JSONDecodeError as e:
print(f"警告: {jsonl_path} 第 {line_num} 行不是有效的 JSON: {e}")
continue
print(f"从 {jsonl_path} 加载了 {annotation_count} 条注释")
else:
print(f"未找到 JSONL 文件: {jsonl_path}")
# 如果是valid分割,与val合并
if split == "valid" and os.path.exists(f"annotations/val_unified.json"):
try:
with open(f"annotations/val_unified.json", "r", encoding="utf-8") as f:
val_annotations = json.load(f)
unified_annotations.extend(val_annotations)
print(f"将valid分割与val分割合并,共 {len(unified_annotations)} 条记录")
except Exception as e:
print(f"合并valid和val分割时出错: {e}")
# 保存统一格式的注释
if unified_annotations:
# 对于valid分割,保存为val_unified.json
save_split = "val" if split == "valid" else split
print(f"为 {save_split} 创建统一格式注释,共 {len(unified_annotations)} 条记录")
unified_path = f"annotations/{save_split}_unified.json"
with open(unified_path, "w", encoding="utf-8") as f:
json.dump(unified_annotations, f, ensure_ascii=False, indent=2)
print(f"已保存统一格式注释到: {unified_path}")
else:
print(f"警告: {split} 没有有效的注释,跳过创建统一格式文件") |