File size: 43,716 Bytes
519ab98 | 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time : 2026/3/17 11:04
@File : feature_data_loader.py.py
@Description :
DeepEllipse 数据加载模块
功能:
- 加载 train/val/test CSV 文件
- 椭圆特征打包为 FeaTensor 列向量,反解后供 section41/42 / deep_elipse_model 使用
- 数据增强:二值化/骨架化 + 旋转 + 仿射变换
- 标签编码:writer_id ↔ label_id 自动转换
"""
import copy
import os
import random
from concurrent.futures import ProcessPoolExecutor, as_completed
from itertools import islice
import cv2
import numpy
import numpy as np
import pandas as pd
import torch
from matplotlib import pyplot as plt
from torch.utils.data import Dataset, DataLoader, Sampler
from torchvision import transforms
from PIL import Image
from sklearn.preprocessing import LabelEncoder
import json
from typing import Optional, Union, List, Tuple, Dict, Sequence
import logging
from augmentation import CircleAugmentation
from elipse_feature import (
DEFAULT_N_THETA,
DEFAULT_N_SEGMENTS,
SegmentGeometry,
FeaTensor,
FeaPackLayout,
FeaFields,
unpack_fea_fields,
extract_ellipse_features,
compute_cwt_scalogram,
compute_fft_amplitude_global,
compute_fft_amplitude_segmented,
)
from image_precess import preprocess_writer_image, resize_image
# from augmentation import CircleAugmentation
from section41 import build_u_man
def _collate_fea_tensor(batch_fea: Sequence[FeaTensor]) -> FeaTensor:
return FeaTensor.stack(batch_fea)
def circle_id_collate_fn(batch):
"""DataLoader collate:FeaTensor 保持紧凑 batch;input_all 可含可选 cwt_scalo。"""
input_alls, labels, pen_ids, writers, image_ids = zip(*batch)
first = input_alls[0]
if len(first) == 2:
ske_list = [ia[0] for ia in input_alls]
img_list = [ia[1] for ia in input_alls]
return (
(None, torch.stack(ske_list, dim=0), torch.stack(img_list, dim=0), None),
torch.tensor(labels),
torch.tensor(pen_ids),
list(writers),
list(image_ids),
)
fea_list = [ia[0] for ia in input_alls]
ske_list = [ia[1] for ia in input_alls]
img_list = [ia[2] for ia in input_alls]
cwt_list = [ia[3] if len(ia) > 3 else None for ia in input_alls]
cwt_batch = None
if cwt_list and all(c is not None for c in cwt_list):
cwt_batch = torch.stack(cwt_list, dim=0)
return (
(
_collate_fea_tensor(fea_list),
torch.stack(ske_list, dim=0),
torch.stack(img_list, dim=0),
cwt_batch,
),
torch.tensor(labels),
torch.tensor(pen_ids),
list(writers),
list(image_ids),
)
class Config:
"""全局配置参数"""
_IS_WINDOWS = os.name == "nt"
# 路径配置(按操作系统自动切换)
if _IS_WINDOWS:
IMAGE_ROOT = r"/path/to/circle_id\data"
DATA_SPLIT_ROOT = r"/path/to/circle_id\data"
TRAIN_CSV = os.path.join(DATA_SPLIT_ROOT, "train.csv")
VAL_CSV = os.path.join(DATA_SPLIT_ROOT, "train.csv")
TEST_CSV = os.path.join(DATA_SPLIT_ROOT, "train.csv")
FEA_CACHE_ROOT = os.path.join(r"/path/to/circle_id", "fea_cache")
else:
IMAGE_ROOT = "/path/to/circle_id/images/"
DATA_SPLIT_ROOT = "/path/to/circle_id/data_split/"
TRAIN_CSV = os.path.join(DATA_SPLIT_ROOT, "train_train3.csv") #"train_train3_our_train.csv" #train_train3.csv
VAL_CSV = os.path.join(DATA_SPLIT_ROOT, "train_val3.csv")
TEST_CSV = os.path.join(DATA_SPLIT_ROOT, "test_with_pen.csv")
FEA_CACHE_ROOT = "/path/to/circle_id_fea_cache" #"/path/to/circle_id/fea_cache/"
# 图像预处理配置
TARGET_SIZE = 100 # 图像目标尺寸
# 数据增强配置
USE_AUGMENT = True
ROTATION_DEGREES = 10 # 随机旋转角度范围 (±10°)
AFFINE_TRANSLATE = 0.03 # 仿射平移比例 (±3%)
AFFINE_SCALE = (0.97, 1.03) # 仿射缩放比例
# 归一化配置 (适配骨架图 [0,255]→[0,1])
NORM_MEAN = [0.5] # 单通道均值
NORM_STD = [0.5] # 单通道标准差
# 日志配置
VERBOSE_DEBUG = False
DEBUG_PREPROCESS = False
DEBUG_SAMPLE_RATIO = 0.01
DEBUG_MIN_SAMPLES = 4
# 椭圆特征配置
N_THETA = DEFAULT_N_THETA # 360
N_SEGMENTS = DEFAULT_N_SEGMENTS # 10
S_L = N_THETA // N_SEGMENTS # 36
FREQ_DIM = 64 # §4.2 输出频率维度
DEEP_FEATURE_DIM = 448 # ResNet深度特征维度
# fea_tensor 预计算缓存(FEA_CACHE_ROOT 见上方路径配置)
PRECOMPUTE_CWT = False
FEA_AUG_VARIANTS = 30 # 每张图预计算增强变体数
USE_PRECOMPUTED_FEA = True
PRECOMPUTE_NUM_WORKERS = 0 # 0 = 自动使用全部 CPU 核心
_NORM_MEAN_SKEL = np.array(0.1, dtype=np.float32).reshape(1, 1, -1)
_NORM_STD_SKEL = np.array(0.3, dtype=np.float32).reshape(1, 1, -1)
_NORM_MEAN_IMG = np.array([0.485, 0.456, 0.406], dtype=np.float32).reshape(1, 1, -1)
_NORM_STD_IMG = np.array([0.229, 0.224, 0.225], dtype=np.float32).reshape(1, 1, -1)
def _fea_cache_path(cache_root: str, image_id: str) -> str:
safe_id = str(image_id).replace(os.sep, "_").replace("/", "_")
return os.path.join(cache_root, f"{safe_id}.pt")
def check_fea_cache_coverage(
csv_path: str,
cache_root: str,
) -> Tuple[int, int, List[str]]:
"""检查 CSV 中样本的 fea 缓存覆盖率。返回 (found, total, missing_sample)。"""
if not os.path.exists(csv_path):
return 0, 0, []
df = pd.read_csv(csv_path)
total = len(df)
found = 0
missing: List[str] = []
for image_id in df["image_id"].astype(str):
if os.path.exists(_fea_cache_path(cache_root, image_id)):
found += 1
elif len(missing) < 5:
missing.append(image_id)
return found, total, missing
def fea_cache_has_cwt(cache_root: str, split: str = "train") -> bool:
"""抽样检查 fea 缓存是否含 cwt_scalo(需 precompute 时加 --precompute-cwt)。"""
split_dir = os.path.join(cache_root, split)
if not os.path.isdir(split_dir):
return False
for name in os.listdir(split_dir):
if not name.endswith(".pt"):
continue
try:
cache = torch.load(
os.path.join(split_dir, name), map_location="cpu", weights_only=False
)
return "cwt_scalo" in cache
except Exception:
continue
return False
def compute_ske_img_tensors(image_bgr: np.ndarray) -> Tuple[torch.Tensor, torch.Tensor]:
"""从 BGR 图像快速计算 ske_tensor / img_tensor(不做椭圆特征提取)。"""
ske = preprocess_writer_image(image_bgr, use_binarization=True, use_skeleton=True)
ske_rgb = cv2.cvtColor(ske, cv2.COLOR_GRAY2RGB) / 255.0
ske_norm = (ske_rgb - _NORM_MEAN_SKEL) / _NORM_STD_SKEL
ske_tensor = torch.FloatTensor(ske_norm).permute(2, 0, 1)
image = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)
img_norm = (image / 255.0 - _NORM_MEAN_IMG) / _NORM_STD_IMG
img_tensor = torch.FloatTensor(img_norm).permute(2, 0, 1)
return ske_tensor, img_tensor
def compute_fea_tensor(image_bgr: np.ndarray) -> Optional[FeaTensor]:
"""从 BGR 图像提取椭圆特征并打包为 FeaTensor(耗时操作)。"""
ske = preprocess_writer_image(image_bgr, use_binarization=True, use_skeleton=True)
bundle = extract_ellipse_features(ske, half_norm=50)
if bundle is None:
return None
valid_count = np.sum(bundle.sequence.interp_flag == 0)
if valid_count < 120:
return None
u_man = build_u_man(bundle.sequence)
amp_global = compute_fft_amplitude_global(u_man[:, :4])
geom = SegmentGeometry(
n_theta=Config.N_THETA,
n_segments=Config.N_SEGMENTS,
s_l=Config.S_L,
half=Config.S_L // 2,
l_win=2 * Config.S_L,
)
amp_segment = compute_fft_amplitude_segmented(u_man[:, :4], geom)
return FeaTensor.from_tensors(
g_global=torch.from_numpy(bundle.global_feat.as_vector()),
u_man=torch.from_numpy(u_man),
amp_global=torch.from_numpy(amp_global.reshape(-1).astype(np.float32)),
amp_segment=torch.from_numpy(amp_segment.reshape(-1).astype(np.float32)),
)
def prepare_model_input_dataloader(image_bgr, only_image=False):
"""
提取椭圆特征并打包为 FeaTensor 列向量。
反解用法(section41 / section42 / deep_elipse_model):
fea = fea_tensor.fields # FeaFields
fea.g_global # (6,)
fea.u_man # (360, 8)
fea.s_res / fea.valid # 由 u_man 派生
fea.amp_global / fea.amp_segment # FFT 幅值,§4.2 输入
"""
ske_tensor, img_tensor = compute_ske_img_tensors(image_bgr)
if only_image is True:
return ske_tensor, img_tensor
fea_tensor = compute_fea_tensor(image_bgr)
if fea_tensor is None:
return None
return fea_tensor, ske_tensor, img_tensor
_worker_augmenter: Optional[CircleAugmentation] = None
def _resolve_num_workers(num_workers: int) -> int:
if num_workers <= 0:
return os.cpu_count() or 4
return num_workers
def _init_precompute_worker() -> None:
"""每个子进程限制 BLAS/OpenCV 线程,避免多进程过度抢占 CPU。"""
os.environ.setdefault("OMP_NUM_THREADS", "1")
os.environ.setdefault("MKL_NUM_THREADS", "1")
os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
torch.set_num_threads(1)
try:
cv2.setNumThreads(1)
except Exception:
pass
def _get_worker_augmenter(use_augment: bool) -> Optional[CircleAugmentation]:
global _worker_augmenter
if not use_augment:
return None
if _worker_augmenter is None:
_worker_augmenter = CircleAugmentation()
return _worker_augmenter
def _precompute_fea_one(task: Dict) -> str:
"""
处理单张图的 fea 预计算(供多进程 worker 调用)。
Returns:
"ok" | "partial" | "fail"
"""
image_id = task["image_id"]
image_path = task["image_path"]
cache_path = task["cache_path"]
target_size = task["target_size"]
num_variants = task["num_variants"]
use_augment = task["use_augment"]
try:
image = cv2.imread(image_path)
if image is None:
return "fail"
augmenter = _get_worker_augmenter(use_augment)
fea_rows: List[torch.Tensor] = []
image_rows: List[np.ndarray] = []
cwt_rows: List[torch.Tensor] = []
precompute_cwt = task.get("precompute_cwt", False)
for _ in range(num_variants):
aug_image = resize_image(image.copy())
if augmenter is not None:
aug_image = augmenter.aug_image(aug_image)
aug_image = resize_image(aug_image, target_size=target_size)
fea_tensor = compute_fea_tensor(aug_image)
if fea_tensor is None:
continue
fea_rows.append(fea_tensor.data.reshape(-1).float())
image_rows.append(aug_image.copy())
if precompute_cwt:
u = fea_tensor.fields.u_man.numpy()
cwt_rows.append(
torch.from_numpy(compute_cwt_scalogram(u[:, :4]).reshape(-1))
)
if not fea_rows:
return "fail"
os.makedirs(os.path.dirname(cache_path) or ".", exist_ok=True)
payload = {
"image_id": image_id,
"fea_data": torch.stack(fea_rows, dim=0),
"images": torch.from_numpy(np.stack(image_rows, axis=0)),
}
if precompute_cwt and cwt_rows:
payload["cwt_scalo"] = torch.stack(cwt_rows, dim=0)
torch.save(payload, cache_path)
if len(fea_rows) < num_variants:
return "partial"
return "ok"
except Exception:
return "fail"
def precompute_fea_cache(
csv_path: str,
image_root: str = Config.IMAGE_ROOT,
cache_root: str = Config.FEA_CACHE_ROOT,
target_size: int = Config.TARGET_SIZE,
num_variants: int = Config.FEA_AUG_VARIANTS,
use_augment: bool = True,
overwrite: bool = False,
num_workers: int = Config.PRECOMPUTE_NUM_WORKERS,
precompute_cwt: bool = False,
verbose: bool = True,
) -> Dict[str, int]:
"""
离线预计算 fea_tensor 并缓存。
每张图随机增强 num_variants 次,每次计算 fea_tensor 并保存对应增强后的图像
(供加载时实时计算 ske/img,保证与 fea 来自同一增强结果)。
缓存文件:{cache_root}/{image_id}.pt
fea_data: (K, L) float32
images: (K, H, W, 3) uint8 BGR
cwt_scalo: (K, 4*40*360) float32 — 可选,precompute_cwt=True
"""
os.makedirs(cache_root, exist_ok=True)
df = pd.read_csv(csv_path)
stats = {"ok": 0, "skip_exists": 0, "fail": 0, "partial": 0}
tasks: List[Dict] = []
for _, row in df.iterrows():
image_id = str(row["image_id"])
cache_path = _fea_cache_path(cache_root, image_id)
if not overwrite and os.path.exists(cache_path):
stats["skip_exists"] += 1
continue
tasks.append(
{
"image_id": image_id,
"image_path": os.path.join(image_root, row["image_path"]),
"cache_path": cache_path,
"target_size": target_size,
"num_variants": num_variants,
"use_augment": use_augment,
"precompute_cwt": precompute_cwt,
}
)
n_workers = _resolve_num_workers(num_workers)
if verbose:
print(f"预计算任务: {len(tasks)} 张待处理, {stats['skip_exists']} 张已跳过, workers={n_workers}")
if not tasks:
if verbose:
print(f"✅ fea 预计算完成 @ {cache_root}: {stats}")
return stats
def _consume_results(result_iter):
for status in result_iter:
stats[status] = stats.get(status, 0) + 1
if n_workers <= 1:
iterator = tasks
if verbose:
try:
from tqdm import tqdm
iterator = tqdm(tasks, desc="precompute fea")
except ImportError:
pass
_consume_results(_precompute_fea_one(task) for task in iterator)
else:
with ProcessPoolExecutor(
max_workers=n_workers,
initializer=_init_precompute_worker,
) as executor:
futures = [executor.submit(_precompute_fea_one, task) for task in tasks]
result_iter = (f.result() for f in as_completed(futures))
if verbose:
try:
from tqdm import tqdm
result_iter = tqdm(result_iter, total=len(futures), desc="precompute fea")
except ImportError:
pass
_consume_results(result_iter)
if verbose:
print(f"✅ fea 预计算完成 @ {cache_root}: {stats}")
return stats
# ================= 核心数据集类 =================
class CircleIDDataset(Dataset):
"""
CircleID 数据集类
支持:
- 加载 CSV 元数据 (image_id, image_path, writer_id, pen_id)
- 预计算特征加载 或 实时特征计算
- 数据增强 (仅实时计算模式)
- 标签编码 (writer_id → label_id)
"""
def __init__(
self,
csv_path: str,
image_root: str = Config.IMAGE_ROOT,
target_size: int = Config.TARGET_SIZE,
transform: Optional[transforms.Compose] = None,
label_encoder: Optional[LabelEncoder] = None,
fit_encoder: bool = False,
sample_ratio: float = 1.0,
min_samples: int = 0,
is_test: bool = False,
enable_augment: bool = True,
use_precomputed_fea: bool = Config.USE_PRECOMPUTED_FEA,
fea_cache_root: str = Config.FEA_CACHE_ROOT,
img_only: bool = False,
verbose: bool = Config.VERBOSE_DEBUG
):
"""
初始化数据集
Args:
csv_path: CSV 文件路径
image_root: 图像根目录
transform: torchvision 变换 (用于图像模式)
label_encoder: LabelEncoder 实例
fit_encoder: 是否拟合 encoder (仅训练集)
sample_ratio: 数据采样比例 (用于调试)
min_samples: 最小采样数量
is_test: 是否为测试集 (无标签)
use_binarization: 是否二值化
use_skeleton: 是否骨架化
enable_augment: 是否随机增强(训练 True,验证/测试 False)
use_precomputed_fea: 是否从缓存加载预计算的 fea_tensor
fea_cache_root: fea_tensor 缓存目录
img_only: True 时仅返回 (ske, img),跳过椭圆 fea 提取
verbose: 是否输出调试信息
"""
self.csv_path = csv_path
self.image_root = image_root
self.target_size = target_size
self.transform = transform
self.is_test = is_test
self.img_only = img_only
self.use_precomputed_fea = use_precomputed_fea
self.fea_cache_root = fea_cache_root
self.enable_augment = enable_augment
# 在线模式:训练集实时随机增强;验证/测试不增强
self.use_online_augment = enable_augment and not use_precomputed_fea
# 预计算模式:训练集随机选取变体;验证/测试固定用第 0 个(无增强)
self.use_random_fea_variant = enable_augment and use_precomputed_fea
self.verbose = verbose
self.error_idx = set()
# 1. 加载 CSV
self.df = pd.read_csv(csv_path)
# 2. 数据采样 (调试用)
if sample_ratio < 1.0 or min_samples > 0:
original_len = len(self.df)
sample_size = max(int(original_len * sample_ratio), min_samples)
sample_size = min(sample_size, original_len)
if sample_size < original_len and verbose:
print(f"📊 数据采样:{original_len} → {sample_size} 张图片")
self.df = self.df.sample(n=sample_size, random_state=42).reset_index(drop=True)
# debug
# self.df = self.df.sample(n=100, random_state=42).reset_index(drop=True)
# 3. 标签编码
self.label_encoder = label_encoder
self._setup_labels(fit_encoder)
# 5. 数据增强器(仅训练集在线模式)
if self.use_online_augment:
self.augmenter = CircleAugmentation()
else:
self.augmenter = None
# 6. 打印统计信息
if verbose:
aug_tag = "随机增强" if self.enable_augment else "无增强"
print(f"✅ 数据集加载完成:{len(self.df)} 张图片 ({aug_tag})" +
(f", {self.df['writer_id'].nunique()} 个 Writer" if not is_test else " (测试集)"))
def _setup_labels(self, fit_encoder: bool):
"""设置标签编码"""
if self.is_test:
# 测试集:无标签
self.num_classes = 0
self.df['label'] = -1
# self.df['pen_id'] = -1
else:
if fit_encoder:
# 训练集:拟合 encoder
self.label_encoder = LabelEncoder()
self.df['label'] = self.label_encoder.fit_transform(self.df['writer_id'])
self.num_classes = len(self.label_encoder.classes_)
if self.verbose:
print(f"🎯 训练集 - Writer 类别数:{self.num_classes}")
elif self.label_encoder is not None:
# 验证集:使用已有 encoder
self.df['label'] = self.df['writer_id'].apply(
lambda x: self.label_encoder.transform([x])[0]
if x in self.label_encoder.classes_ else -1
)
self.num_classes = len(self.label_encoder.classes_)
else:
raise ValueError("验证集需要提供 label_encoder")
def __len__(self) -> int:
return len(self.df)
def _load_from_fea_cache(self, image_id: str) -> Optional[Tuple[FeaTensor, torch.Tensor, torch.Tensor]]:
"""从缓存加载 fea;训练集随机选变体,验证/测试固定用第 0 个。"""
cache_path = _fea_cache_path(self.fea_cache_root, image_id)
if not os.path.exists(cache_path):
return None
cache = torch.load(cache_path, map_location="cpu", weights_only=False)
fea_data = cache["fea_data"]
images = cache["images"]
n_variants = fea_data.shape[0]
if n_variants == 0:
return None
if self.use_random_fea_variant:
variant_idx = random.randint(0, n_variants - 1)
else:
variant_idx = 0
fea_tensor = FeaTensor(data=fea_data[variant_idx])
image_bgr = images[variant_idx].numpy()
if image_bgr.dtype != np.uint8:
image_bgr = image_bgr.astype(np.uint8)
ske_tensor, img_tensor = compute_ske_img_tensors(image_bgr)
cwt_tensor = None
if "cwt_scalo" in cache:
flat = cache["cwt_scalo"][variant_idx]
cwt_tensor = flat.view(4, 40, Config.N_THETA).float()
if cwt_tensor is not None:
return fea_tensor, ske_tensor, img_tensor, cwt_tensor
return fea_tensor, ske_tensor, img_tensor
def __getitem__(self, idx: int):
"""
获取单个样本
Returns:
feature: (40, 120) 特征张量 [C, L]
label: writer_id 编码 (-1 表示测试集)
pen_id: 笔的标识
writer_id: 原始 writer_id 字符串
"""
if idx in self.error_idx:
new_index = np.random.randint(0, len(self.df))
return self.__getitem__(new_index)
row = self.df.iloc[idx]
pen_id = row['pen_id']
# row['image_path'] = "images/00295.png" # debug
image_path = os.path.join(self.image_root, row['image_path'])
writer_id = str(row['writer_id']) if 'writer_id' in row else ''
label = row['label'] if not self.is_test else -1
image_id = str(row['image_id'])
if self.use_precomputed_fea:
cached = self._load_from_fea_cache(image_id)
if cached is not None:
if self.img_only:
_, ske_tensor, img_tensor = cached[:3]
return (ske_tensor, img_tensor), label, pen_id, writer_id, image_id
return cached, label, pen_id, writer_id, image_id
image = cv2.imread(image_path) # BGR
if image is None:
self.error_idx.add(idx)
new_index = np.random.randint(0, len(self.df))
return self.__getitem__(new_index)
try:
if self.augmenter is not None:
image = resize_image(image)
image = self.augmenter.aug_image(image)
# image = self.augmenter.aug_image_offical(image)
image = resize_image(image)
# 与 §4.1 / ResNet 输入一致:保持长宽比缩放并 pad 到 target_size×target_size
image = resize_image(image, target_size=self.target_size)
input_all = prepare_model_input_dataloader(
image, only_image=self.img_only,
)
if input_all is None and not self.img_only:
self.error_idx.add(idx)
new_index = np.random.randint(0, len(self.df))
return self.__getitem__(new_index)
else:
return input_all, label, pen_id, writer_id, image_id
except Exception as e:
print(f"\n❌ [ERROR] idx={idx}, image_id={image_id}, writer_id={writer_id}")
print(f" Exception: {type(e).__name__}: {e}")
import traceback
traceback.print_exc()
self.error_idx.add(idx)
new_index = np.random.randint(0, len(self.df))
# cv2.imwrite(f"/path/to/circle_id/circle_output/polar_order/temp/fail_elipse_{image_id}.png", image)
return self.__getitem__(new_index)
def get_label_encoder(self) -> Optional[LabelEncoder]:
"""获取标签编码器 (用于测试集解码)"""
return self.label_encoder
def get_writer_by_label(self, label: int) -> Optional[str]:
"""根据 label_id 获取 writer_id"""
if self.label_encoder is not None and 0 <= label < len(self.label_encoder.classes_):
return self.label_encoder.classes_[label]
return None
def _build_writer_label_pools(
labels: Sequence[int],
*,
exclude_label: int = -1,
) -> Tuple[Dict[int, List[int]], List[int]]:
label_to_indices: Dict[int, List[int]] = {}
for idx, lab in enumerate(labels):
li = int(lab)
if li == exclude_label:
continue
label_to_indices.setdefault(li, []).append(idx)
return label_to_indices, sorted(label_to_indices.keys())
def parse_pk_mix(pk_mix: str) -> List[Tuple[int, int]]:
"""Parse '4,128;8,64' into [(4,128), (8,64)]; all configs must share P*K."""
configs: List[Tuple[int, int]] = []
for part in pk_mix.split(";"):
part = part.strip()
if not part:
continue
chunks = [c.strip() for c in part.split(",") if c.strip()]
if len(chunks) != 2:
raise ValueError(
f"Invalid pk_mix segment {part!r}; expected 'P,K' (e.g. 4,128)"
)
p, k = int(chunks[0]), int(chunks[1])
if p <= 0 or k <= 0:
raise ValueError(f"PK values must be positive, got P={p}, K={k}")
configs.append((p, k))
if not configs:
raise ValueError(f"pk_mix is empty: {pk_mix!r}")
batch_sizes = {p * k for p, k in configs}
if len(batch_sizes) != 1:
raise ValueError(f"All PK configs must have the same P*K, got {configs}")
return configs
def _sample_pk_batch(
label_to_indices: Dict[int, List[int]],
writer_labels: Sequence[int],
*,
p: int,
k: int,
) -> List[int]:
chosen = random.sample(list(writer_labels), p)
batch: List[int] = []
for lab in chosen:
pool = label_to_indices[lab]
if len(pool) >= k:
batch.extend(random.sample(pool, k))
else:
batch.extend(random.choices(pool, k=k))
return batch
class WriterPKBatchSampler(Sampler):
"""Yields batch index lists: P writers × K images; excludes ignore_label."""
def __init__(
self,
labels: Sequence[int],
*,
p: int,
k: int,
exclude_label: int = -1,
num_batches: Optional[int] = None,
):
if p <= 0 or k <= 0:
raise ValueError(f"p and k must be positive, got p={p}, k={k}")
self.p = int(p)
self.k = int(k)
self.batch_size = self.p * self.k
self.label_to_indices, self.labels = _build_writer_label_pools(
labels, exclude_label=exclude_label
)
if len(self.labels) < self.p:
raise ValueError(
f"WriterPKBatchSampler: need at least {self.p} writers, "
f"got {len(self.labels)}"
)
total = sum(len(v) for v in self.label_to_indices.values())
self._num_batches = int(
num_batches if num_batches is not None else max(1, total // self.batch_size)
)
self.last_pk: Optional[Tuple[int, int]] = (self.p, self.k)
def __len__(self) -> int:
return self._num_batches
def __iter__(self):
for _ in range(self._num_batches):
self.last_pk = (self.p, self.k)
yield _sample_pk_batch(
self.label_to_indices, self.labels, p=self.p, k=self.k
)
class WriterPKMixBatchSampler(Sampler):
"""Each batch randomly picks one (P,K) from pk_configs; all must share P*K."""
def __init__(
self,
labels: Sequence[int],
*,
pk_configs: Sequence[Tuple[int, int]],
exclude_label: int = -1,
num_batches: Optional[int] = None,
):
self.pk_configs = [(int(p), int(k)) for p, k in pk_configs]
batch_sizes = {p * k for p, k in self.pk_configs}
if len(batch_sizes) != 1:
raise ValueError(
f"WriterPKMixBatchSampler: all configs need same P*K, got {self.pk_configs}"
)
self.batch_size = batch_sizes.pop()
self.max_p = max(p for p, _ in self.pk_configs)
self.label_to_indices, self.labels = _build_writer_label_pools(
labels, exclude_label=exclude_label
)
if len(self.labels) < self.max_p:
raise ValueError(
f"WriterPKMixBatchSampler: need at least {self.max_p} writers, "
f"got {len(self.labels)}"
)
total = sum(len(v) for v in self.label_to_indices.values())
self._num_batches = int(
num_batches if num_batches is not None else max(1, total // self.batch_size)
)
self.last_pk: Optional[Tuple[int, int]] = None
def __len__(self) -> int:
return self._num_batches
def __iter__(self):
for _ in range(self._num_batches):
p, k = random.choice(self.pk_configs)
self.last_pk = (p, k)
yield _sample_pk_batch(
self.label_to_indices, self.labels, p=p, k=k
)
def _dataloader_extra_kwargs(
num_workers: int,
prefetch_factor: Optional[int],
) -> dict:
extra: dict = {}
if num_workers > 0 and prefetch_factor is not None:
extra["prefetch_factor"] = int(prefetch_factor)
extra["persistent_workers"] = False
return extra
# ================= 数据加载器工厂 =================
def create_dataloaders(
batch_size: int = 32,
num_workers: int = 32,
pin_memory: bool = True,
sample_ratio: float = 1.0,
min_samples: int = 0,
use_precomputed: bool = True,
fea_cache_root: Optional[str] = None,
img_only: bool = False,
verbose: bool = True,
pk_p: Optional[int] = None,
pk_k: Optional[int] = None,
pk_mix: Optional[str] = None,
pk_exclude_label: int = -1,
eval_batch_size: Optional[int] = None,
prefetch_factor: Optional[int] = None,
) -> Tuple[DataLoader, DataLoader, Optional[DataLoader], LabelEncoder]:
"""
创建训练/验证/测试数据加载器。
增强策略:训练集随机增强;验证集、测试集不增强。
Returns:
train_loader, val_loader, test_loader, label_encoder
"""
cache_root = fea_cache_root or Config.FEA_CACHE_ROOT
if use_precomputed and verbose:
split_specs = [
("train", Config.TRAIN_CSV),
("val", Config.VAL_CSV),
]
if os.path.exists(Config.TEST_CSV):
split_specs.append(("test", Config.TEST_CSV))
precompute_hint_printed = False
for split_name, csv_path in split_specs:
found, total, missing = check_fea_cache_coverage(
csv_path, os.path.join(cache_root, split_name)
)
pct = 100.0 * found / max(total, 1)
print(f"fea 缓存 [{split_name}]: {found}/{total} ({pct:.1f}%)")
if found < total:
print(f" 警告: {split_name} 缺 {total - found} 个缓存", end="")
if missing:
print(f",示例 id: {missing[:3]}")
else:
print()
if not precompute_hint_printed:
print(
" 补全命令: python exp6_data_loader.py "
"--precompute-fea --split val_test --precompute-cwt"
)
precompute_hint_printed = True
# 1. 创建训练集 (拟合 label encoder,随机增强)
train_dataset = CircleIDDataset(
csv_path=Config.TRAIN_CSV,
image_root=Config.IMAGE_ROOT,
fit_encoder=True,
sample_ratio=sample_ratio,
min_samples=min_samples,
is_test=False,
enable_augment=True,
use_precomputed_fea=use_precomputed,
fea_cache_root=os.path.join(cache_root, "train"),
img_only=img_only,
verbose=verbose
)
label_encoder = train_dataset.label_encoder
# 2. 创建验证集 (使用已有 encoder,不增强)
val_dataset = CircleIDDataset(
csv_path=Config.VAL_CSV,
image_root=Config.IMAGE_ROOT,
label_encoder=label_encoder,
fit_encoder=False,
is_test=False,
enable_augment=False,
use_precomputed_fea=use_precomputed,
fea_cache_root=os.path.join(cache_root, "val"),
img_only=img_only,
verbose=verbose
)
eval_bs = int(eval_batch_size) if eval_batch_size is not None else int(batch_size)
worker_kw = _dataloader_extra_kwargs(num_workers, prefetch_factor)
# 3. 创建测试集 (可选,不增强)
if os.path.exists(Config.TEST_CSV):
test_dataset = CircleIDDataset(
csv_path=Config.TEST_CSV,
image_root=Config.IMAGE_ROOT,
label_encoder=label_encoder,
is_test=True,
enable_augment=False,
use_precomputed_fea=use_precomputed,
fea_cache_root=os.path.join(cache_root, "test"),
img_only=img_only,
verbose=verbose
)
test_loader = DataLoader(
test_dataset,
batch_size=eval_bs,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
collate_fn=circle_id_collate_fn,
**worker_kw,
)
else:
test_loader = None
if verbose:
print(f"⚠️ 测试集文件不存在: {Config.TEST_CSV}")
# 4. 创建 DataLoader
train_batch_sampler = None
if pk_mix:
pk_configs = parse_pk_mix(pk_mix)
train_labels = train_dataset.df["label"].astype(int).tolist()
train_batch_sampler = WriterPKMixBatchSampler(
train_labels,
pk_configs=pk_configs,
exclude_label=pk_exclude_label,
)
if verbose:
cfg_str = ", ".join(f"P{p}K{k}" for p, k in pk_configs)
print(
f" Train PK mix batch_sampler: [{cfg_str}], "
f"batch={train_batch_sampler.batch_size}, "
f"writers={len(train_batch_sampler.labels)}, "
f"batches/epoch={len(train_batch_sampler)}"
)
elif pk_p is not None and pk_k is not None:
train_labels = train_dataset.df["label"].astype(int).tolist()
train_batch_sampler = WriterPKBatchSampler(
train_labels, p=int(pk_p), k=int(pk_k), exclude_label=pk_exclude_label
)
if verbose:
print(
f" Train PK batch_sampler: P={pk_p}, K={pk_k}, "
f"batch={int(pk_p) * int(pk_k)}, writers={len(train_batch_sampler.labels)}, "
f"batches/epoch={len(train_batch_sampler)}"
)
if train_batch_sampler is not None:
train_loader = DataLoader(
train_dataset,
batch_sampler=train_batch_sampler,
num_workers=num_workers,
pin_memory=pin_memory,
collate_fn=circle_id_collate_fn,
**worker_kw,
)
else:
train_loader = DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=pin_memory,
drop_last=True,
collate_fn=circle_id_collate_fn,
**worker_kw,
)
val_loader = DataLoader(
val_dataset,
batch_size=eval_bs,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
collate_fn=circle_id_collate_fn,
**worker_kw,
)
if verbose:
print(f"📦 DataLoader 创建完成:")
if use_precomputed:
print(f" fea 缓存: {cache_root}/{{train,val,test}}")
print(f" 训练: 随机选取增强变体 | 验证/测试: 固定原图变体")
print(f" Train: {len(train_dataset)} samples, {len(train_loader)} batches (增强)")
print(f" Val: {len(val_dataset)} samples, {len(val_loader)} batches (无增强)")
if test_loader:
print(f" Test: {len(test_dataset)} samples, {len(test_loader)} batches (无增强)")
return train_loader, val_loader, test_loader, label_encoder
def merge_csv():
import pandas as pd
# 1. 定义文件路径
# 请替换为你实际的文件路径
csv_path_1 = "/path/to/circle_id/data_split/our_train.csv"
csv_path_2 = "/path/to/circle_id/data_split/train_train3.csv"
output_path = "/path/to/circle_id/data_split/train_train3_our_train.csv"
# 2. 读取两个 CSV 文件
df1 = pd.read_csv(csv_path_1)
df2 = pd.read_csv(csv_path_2)
# 3. 合并数据 (上下拼接)
# ignore_index=True 会重新生成连续的索引 (0, 1, 2...),避免索引重复
merged_df = pd.concat([df1, df2], ignore_index=True)
# 4. 保存为新的 CSV 文件
# index=False 表示保存时不包含行索引列
merged_df.to_csv(output_path, index=False)
print(f"合并完成!新文件已保存至: {output_path}")
print(f"原始数据行数: {len(df1)} + {len(df2)} = {len(merged_df)}")
def build_test_loader(
csv_path: str,
*,
class_names: Sequence[str],
fea_cache_root: Optional[str] = None,
image_root: Optional[str] = None,
batch_size: int = 128,
num_workers: int = 8,
pin_memory: bool = True,
) -> Tuple[DataLoader, LabelEncoder]:
"""Build a *test-only* loader (no train/val datasets, no augmentation).
Released inference needs the test split alone, so unlike
:func:`create_dataloaders` this never materialises the training or
validation datasets -- and therefore never touches the (large) training
feature cache. The label encoder is taken from the released class-name
list instead of being fitted on the training CSV.
Returns (test_loader, label_encoder).
"""
encoder = LabelEncoder()
encoder.classes_ = pd.Index([str(c) for c in class_names])
cache_root = fea_cache_root or Config.FEA_CACHE_ROOT
dataset = CircleIDDataset(
csv_path=csv_path,
image_root=image_root or Config.IMAGE_ROOT,
label_encoder=encoder,
fit_encoder=False,
is_test=True,
enable_augment=False,
use_precomputed_fea=True,
fea_cache_root=os.path.join(cache_root, "test"),
verbose=False,
)
loader = DataLoader(
dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
collate_fn=circle_id_collate_fn,
)
return loader, encoder
# ================= 测试代码 =================
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="CircleID data loader")
parser.add_argument(
"--precompute-fea",
default=True,
help="离线预计算 fea_tensor 缓存",
)
parser.add_argument(
"--split",
choices=["train", "val", "test", "val_test", "all"],
default="all",
help="预计算划分:val_test=仅 val+test(train 已有缓存时用);all=train+val+test",
)
parser.add_argument(
"--num-variants",
type=int,
default=Config.FEA_AUG_VARIANTS,
help="每张图随机增强并预计算的变体数",
)
parser.add_argument(
"--cache-root",
type=str,
default=Config.FEA_CACHE_ROOT,
help="fea_tensor 缓存目录",
)
parser.add_argument(
"--precompute-cwt",
action="store_true",
help="fea 预计算时同时缓存 cwt_scalo (4×40×360)",
)
parser.add_argument(
"--train-augment",
default=True,
help="训练集做随机增强",
)
parser.add_argument(
"--num-workers",
type=int,
default=Config.PRECOMPUTE_NUM_WORKERS,
help="预计算进程数,0 表示自动使用全部 CPU 核心",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="覆盖已有缓存",
)
args = parser.parse_args()
if args.precompute_fea:
split_csv = {
"train": Config.TRAIN_CSV,
"val": Config.VAL_CSV,
"test": Config.TEST_CSV,
}
splits = list(split_csv.keys()) if args.split == "all" else (
["val", "test"] if args.split == "val_test" else [args.split]
)
for split in splits:
csv_path = split_csv[split]
if not os.path.exists(csv_path):
print(f"⚠️ 跳过 {split}: {csv_path} 不存在")
continue
split_use_augment = (split == "train") and args.train_augment
split_num_variants = args.num_variants if split == "train" else 1
split_cache_root = os.path.join(args.cache_root, split)
print(f"\n=== 预计算 {split} (augment={split_use_augment}, variants={split_num_variants}, workers={args.num_workers or 'auto'}) ===")
precompute_fea_cache(
csv_path=csv_path,
cache_root=split_cache_root,
num_variants=split_num_variants,
use_augment=split_use_augment,
overwrite=args.overwrite,
num_workers=args.num_workers,
precompute_cwt=args.precompute_cwt,
)
raise SystemExit(0)
# 简单测试
print("测试 DeepEllipse data_loader")
# 1. 测试单样本加载
dataset = CircleIDDataset(
csv_path=Config.TRAIN_CSV,
sample_ratio=1,
fit_encoder=True,
enable_augment=True,
verbose=True
)
input_all, label, pen_id, writer_id, image_id = dataset[0]
fea_tensor, ske_tensor, img_tensor, *_ = input_all
fea = fea_tensor.fields
print(f"样本:")
print(f" data column: {fea_tensor.data.shape} len={FeaPackLayout.len_core()}")
print(f" g_global: {fea.g_global.shape} u_man: {fea.u_man.shape}")
print(f" s_res: {fea.s_res.shape} valid: {fea.valid.shape}")
print(f" amp_global: {fea.amp_global.shape} amp_segment: {fea.amp_segment.shape}")
print(f" ske: {ske_tensor.shape}, img: {img_tensor.shape}")
print(f" Label: {label}, pen_id: {pen_id}, Writer: {writer_id}")
# 2. 测试 DataLoader
train_loader, val_loader, test_loader, encoder = create_dataloaders(
num_workers=1,
batch_size=4,
sample_ratio=0.001,
verbose=True
)
loader = test_loader if test_loader is not None else train_loader
loader_name = "test" if test_loader is not None else "train"
for batch_idx, batch in enumerate(islice(loader, 10)):
input_all, label, pen_id, writer_id, image_id = batch
fea_tensor, ske_tensor, img_tensor = input_all
fea = fea_tensor.fields
print(f"[{loader_name} batch {batch_idx}] data={fea_tensor.data.shape}, "
f"u_man={fea.u_man.shape}, amp_seg={fea.amp_segment.shape}")
print(f" Label: {label}, pen_id: {pen_id}, Writer: {writer_id}")
print("所有测试通过!")
|