File size: 23,059 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Time    : 2026/3/17 16:54 
@File    : sift_feature_optimized.py
@Description: 高性能 SIFT 特征提取 (整图预计算 + 向量化)
"""

import os
import time

import cv2
import numpy as np
from pathlib import Path
import json

from matplotlib import pyplot as plt
from tqdm import tqdm
from typing import List, Tuple, Optional

# ================= 配置参数 =================
DEFAULT_IMAGE_FOLDER = "/path/to/circle_id/images/images"
DEFAULT_FEATURE_FOLDER = "/path/to/circle_id/outputs/polar_order"
DEFAULT_OUTPUT_FOLDER = "/path/to/circle_id/outputs/sift_features"

# 🔧 SIFT 参数
PADDING_SIZE = 7  # 边界填充 (≥ patch_size//2)
PATCH_SIZE = 12  # 🔧 描述子计算区域 (12×12 像素)
GRID_SIZE = 2  # 🔧 子区域网格 (2×2)
N_ORIENTATION_BINS = 8  # 方向直方图 bin 数
DESCRIPTOR_DIM = GRID_SIZE * GRID_SIZE * N_ORIENTATION_BINS  # 2×2×8 = 32 维

# 关键点配置
KEYPOINT_ANGLE = 0.0  # 固定方向,保留原始方向信息
KEYPOINT_SIZE = 8.0

MATCHED_POINTS_FILE_SUFFIX = '_matched_points.npy'


# ================= 1. 预计算工具函数 =================

def precompute_gradients(image_gray: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    """
    🔧 整图预计算梯度幅值和方向

    返回:
        magnitude: (H, W) 梯度幅值
        orientation: (H, W) 梯度方向 (0~360°)
    """
    # Sobel 计算梯度 (使用 CV_32F 保证精度)
    gx = cv2.Sobel(image_gray, cv2.CV_32F, 1, 0, ksize=1)
    gy = cv2.Sobel(image_gray, cv2.CV_32F, 0, 1, ksize=1)

    # 幅值和方向
    magnitude = np.sqrt(gx ** 2 + gy ** 2, dtype=np.float32)
    orientation = np.arctan2(gy, gx, dtype=np.float32)
    orientation = np.degrees(orientation)
    orientation = (orientation + 360) % 360  # 归一化到 0~360

    return magnitude, orientation


def create_gaussian_weight(patch_size: int, sigma: Optional[float] = None) -> np.ndarray:
    """
    🔧 预计算高斯权重模板

    返回:
        weight: (patch_size, patch_size) 高斯权重
    """
    if sigma is None:
        sigma = patch_size / 2.0

    center = patch_size / 2.0
    y_grid, x_grid = np.mgrid[0:patch_size, 0:patch_size]

    weight = np.exp(-((x_grid - center) ** 2 + (y_grid - center) ** 2) / (2 * sigma ** 2))
    return weight.astype(np.float32)


def extract_patch_vectorized(data: np.ndarray, centers: np.ndarray,
                             patch_size: int, image_shape: Tuple[int, int],
                             padding: int) -> np.ndarray:
    """
    🔧 批量提取多个位置的 patch (向量化版本)

    参数:
        data: 预计算的全图数据 (H, W) 或 (H, W, C)
        centers: (N, 2) 关键点坐标 [(x1,y1), (x2,y2), ...]
        patch_size: patch 尺寸
        image_shape: 原始图像尺寸 (H, W)
        padding: 预填充的像素数

    返回:
        patches: (N, patch_size, patch_size) 批量提取的 patch
    """
    n_points = len(centers)
    half_patch = patch_size // 2

    # 调整坐标到填充后的图像
    centers_padded = centers + padding  # (N, 2)

    patches = []
    for cx, cy in centers_padded:
        x_min = max(0, int(cx) - half_patch)
        x_max = min(image_shape[1] + 2 * padding, int(cx) + half_patch)
        y_min = max(0, int(cy) - half_patch)
        y_max = min(image_shape[0] + 2 * padding, int(cy) + half_patch)

        patch = data[y_min:y_max, x_min:x_max]

        # 如果边界不足,填充
        if patch.shape[0] < patch_size or patch.shape[1] < patch_size:
            pad_top = half_patch - (int(cy) - y_min)
            pad_bottom = patch_size - patch.shape[0] - pad_top
            pad_left = half_patch - (int(cx) - x_min)
            pad_right = patch_size - patch.shape[1] - pad_left
            patch = cv2.copyMakeBorder(patch, pad_top, pad_bottom, pad_left, pad_right,
                                       borderType=cv2.BORDER_REFLECT_101)

        patches.append(patch)

    return np.array(patches, dtype=np.float32)  # (N, patch_size, patch_size)


def compute_histogram_vectorized(magnitude: np.ndarray, orientation: np.ndarray,
                                 n_bins: int = 8) -> np.ndarray:
    """
    🔧 向量化计算方向直方图

    参数:
        magnitude: (H, W) 梯度幅值
        orientation: (H, W) 梯度方向 (0~360°)
        n_bins: 方向 bin 数量

    返回:
        hist: (n_bins,) 方向直方图
    """
    # 展平
    mag_flat = magnitude.ravel()
    ori_flat = orientation.ravel()

    # 计算 bin 索引 (0~360° → 0~n_bins-1)
    bin_indices = (ori_flat / (360 / n_bins)).astype(np.int32) % n_bins

    # 向量化投票 (使用 bincount + weights)
    hist = np.bincount(bin_indices, weights=mag_flat, minlength=n_bins)

    return hist.astype(np.float32)


# ================= 2. 优化版描述子计算 =================

def compute_custom_sift_descriptor_optimized(
        magnitude_full: np.ndarray,
        orientation_full: np.ndarray,
        x: float, y: float,
        image_shape: Tuple[int, int],
        padding: int,
        patch_size: int = PATCH_SIZE,
        grid_size: int = GRID_SIZE,
        n_bins: int = N_ORIENTATION_BINS,
        gaussian_weight: Optional[np.ndarray] = None
) -> Tuple[np.ndarray, bool]:
    """
    🔧 优化版:使用预计算梯度 + 向量化直方图

    参数:
        magnitude_full: 预计算的全图梯度幅值 (H+2*padding, W+2*padding)
        orientation_full: 预计算的全图梯度方向
        x, y: 关键点坐标 (原始图像坐标系)
        image_shape: 原始图像尺寸 (H, W)
        padding: 预填充像素数
        ... 其他参数同上

    返回:
        descriptor: (32,) 描述子向量
        success: 是否成功
    """
    if x == -1 and y == -1:
        # print("point -1")
        return np.zeros(DESCRIPTOR_DIM, dtype=np.float32), False

    half_patch = patch_size // 2
    kp_x, kp_y = x + padding, y + padding  # 转换到填充后坐标

    # 1. 提取单个 patch 的幅值和方向
    x_min = max(0, int(kp_x) - half_patch)
    x_max = min(image_shape[1] + 2 * padding, int(kp_x) + half_patch)
    y_min = max(0, int(kp_y) - half_patch)
    y_max = min(image_shape[0] + 2 * padding, int(kp_y) + half_patch)

    mag_patch = magnitude_full[y_min:y_max, x_min:x_max]
    ori_patch = orientation_full[y_min:y_max, x_min:x_max]

    # 边界填充
    if mag_patch.shape[0] < patch_size or mag_patch.shape[1] < patch_size:
        pad_top = half_patch - (int(kp_y) - y_min)
        pad_bottom = patch_size - mag_patch.shape[0] - pad_top
        pad_left = half_patch - (int(kp_x) - x_min)
        pad_right = patch_size - mag_patch.shape[1] - pad_left
        mag_patch = cv2.copyMakeBorder(mag_patch, pad_top, pad_bottom, pad_left, pad_right,
                                       borderType=cv2.BORDER_REFLECT_101)
        ori_patch = cv2.copyMakeBorder(ori_patch, pad_top, pad_bottom, pad_left, pad_right,
                                       borderType=cv2.BORDER_REFLECT_101)

    if mag_patch.shape != (patch_size, patch_size):
        return np.zeros(grid_size * grid_size * n_bins, dtype=np.float32), False

    # 2. 应用高斯权重
    if gaussian_weight is None:
        gaussian_weight = create_gaussian_weight(patch_size)
    mag_weighted = mag_patch * gaussian_weight

    # 3. 划分为 2×2 子区域 + 向量化直方图
    subregion_size = patch_size // grid_size
    descriptor = []

    for i in range(grid_size):
        for j in range(grid_size):
            y_start = i * subregion_size
            y_end = (i + 1) * subregion_size
            x_start = j * subregion_size
            x_end = (j + 1) * subregion_size

            sub_mag = mag_weighted[y_start:y_end, x_start:x_end]
            sub_ori = ori_patch[y_start:y_end, x_start:x_end]

            # 🔧 向量化直方图计算
            hist = compute_histogram_vectorized(sub_mag, sub_ori, n_bins)
            descriptor.extend(hist)

    descriptor = np.array(descriptor, dtype=np.float32)

    # 4. L2 归一化 + 截断
    norm = np.linalg.norm(descriptor)
    if norm > 1e-10:
        descriptor = descriptor / norm

    descriptor = np.clip(descriptor, 0.0, 0.2)

    norm = np.linalg.norm(descriptor)
    if norm > 1e-10:
        descriptor = descriptor / norm

    return descriptor, True


# ================= 3. 批量提取器 (核心优化) =================

class SIFTFeatureExtractorOptimized:
    """
    🔧 高性能 SIFT 特征提取器

    优化策略:
    1. 整图预计算梯度 (避免 120 次重复)
    2. 预计算高斯权重模板
    3. 向量化直方图计算 (替代嵌套 for)
    4. 批量处理关键点
    """

    def __init__(self,
                 patch_size: int = PATCH_SIZE,
                 grid_size: int = GRID_SIZE,
                 n_bins: int = N_ORIENTATION_BINS,
                 padding_size: int = PADDING_SIZE):
        self.patch_size = patch_size
        self.grid_size = grid_size
        self.n_bins = n_bins
        self.padding_size = padding_size
        self.descriptor_dim = grid_size * grid_size * n_bins

        # 🔧 预计算高斯权重 (只需计算一次)
        self.gaussian_weight = create_gaussian_weight(patch_size)

    def extract_batch(self, image_gray: np.ndarray, points: List[Tuple[float, float]]) -> Tuple[np.ndarray, np.ndarray]:
        """
        🔧 批量提取多个关键点的 SIFT 描述子

        参数:
            image_gray: 灰度图像 (H, W)
            points: [(x1,y1), (x2,y2), ...] 关键点列表

        返回:
            descriptors: (N, 32) 描述子矩阵
            success_mask: (N,) 成功标记
        """
        h, w = image_gray.shape
        n_points = len(points)

        if n_points == 0:
            return np.zeros((0, self.descriptor_dim), dtype=np.float32), np.zeros(0, dtype=bool)

        # 🔧 1. 整图预计算梯度 (最大优化点!)
        magnitude_full, orientation_full = precompute_gradients(image_gray)

        # 🔧 2. 整图边界填充 (只需一次)
        magnitude_full = cv2.copyMakeBorder(
            magnitude_full,
            top=self.padding_size, bottom=self.padding_size,
            left=self.padding_size, right=self.padding_size,
            borderType=cv2.BORDER_REFLECT_101
        )
        orientation_full = cv2.copyMakeBorder(
            orientation_full,
            top=self.padding_size, bottom=self.padding_size,
            left=self.padding_size, right=self.padding_size,
            borderType=cv2.BORDER_REFLECT_101
        )

        # 🔧 3. 批量处理每个关键点
        descriptors = np.zeros((n_points, self.descriptor_dim), dtype=np.float32)
        success_mask = np.zeros(n_points, dtype=bool)

        for i, point in enumerate(points):
            if point is None:
                continue

            x, y = point
            desc, success = compute_custom_sift_descriptor_optimized(
                magnitude_full, orientation_full,
                x, y,
                image_shape=(h, w),
                padding=self.padding_size,
                patch_size=self.patch_size,
                grid_size=self.grid_size,
                n_bins=self.n_bins,
                gaussian_weight=self.gaussian_weight
            )
            descriptors[i] = desc
            success_mask[i] = success

        return descriptors, success_mask

    def extract_at_points(self, image_gray: np.ndarray, points: List[Tuple[float, float]]) -> Tuple[
        np.ndarray, np.ndarray]:
        """兼容接口:调用批量提取"""
        return self.extract_batch(image_gray, points)


# ================= 4. 单图像提取 (使用优化版) =================

def extract_sift_for_single_image(image_path: str, matched_points_path: str,
                                  extractor: SIFTFeatureExtractorOptimized,
                                  output_dir: str) -> Optional[dict]:
    """为单张图像提取 SIFT 特征 (使用优化版提取器)"""
    # 1. 加载图像
    img = cv2.imread(image_path)
    if img is None:
        print(f"  ❌ 无法读取图像:{image_path}")
        return None

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else img

    # 2. 加载 matched_points
    if not os.path.exists(matched_points_path):
        print(f"  ❌ 找不到 matched_points 文件:{matched_points_path}")
        return None

    matched_points = np.load(matched_points_path, allow_pickle=True)

    # 转换为列表格式
    points_list = []
    for mp in matched_points:
        if mp is None or (isinstance(mp, np.ndarray) and mp.size == 0):
            points_list.append(None)
        elif isinstance(mp, (tuple, list, np.ndarray)):
            points_list.append(tuple(mp))
        else:
            points_list.append(None)

    n_points = len(points_list)
    if n_points == 0:
        print(f"  ⚠️  无有效坐标点:{matched_points_path}")
        return None

    # 3. 🔧 批量提取 (优化版)
    descriptors, success_mask = extractor.extract_batch(img_gray, points_list)

    # 4. 保存结果
    base_name = Path(image_path).stem
    sift_path = os.path.join(output_dir, f'{base_name}_sift.npy')
    np.save(sift_path, descriptors)

    success_path = os.path.join(output_dir, f'{base_name}_sift_success.npy')
    np.save(success_path, success_mask)

    # 5. 生成报告
    success_count = int(np.sum(success_mask))
    report = {
        'image_path': image_path,
        'matched_points_path': matched_points_path,
        'image_size': {'width': int(img_gray.shape[1]), 'height': int(img_gray.shape[0])},
        'n_points': n_points,
        'success_count': success_count,
        'success_rate': float(success_count / n_points) if n_points > 0 else 0.0,
        'descriptor_config': {
            'patch_size': PATCH_SIZE,
            'grid_size': GRID_SIZE,
            'n_orientation_bins': N_ORIENTATION_BINS,
            'descriptor_dim': DESCRIPTOR_DIM,
            'keypoint_angle': KEYPOINT_ANGLE,
            'keypoint_size': KEYPOINT_SIZE,
            'rotation_invariant': False,
            'optimization': 'precomputed_gradients_vectorized_histogram'
        },
        'padding_size': PADDING_SIZE,
        'output_files': {
            'sift_descriptors': sift_path,
            'success_mask': success_path
        }
    }

    report_path = os.path.join(output_dir, f'{base_name}_sift_report.json')
    with open(report_path, 'w') as f:
        json.dump(report, f, indent=2)

    return {
        'descriptors': descriptors,
        'success_mask': success_mask,
        'report': report
    }


def extract_sift_for_single_image_pure(img, matched_points, extractor):
    """为单张图像提取 SIFT 特征 (使用优化版提取器)"""
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else img

    points_list = []
    for mp in matched_points:
        if mp is None or (isinstance(mp, np.ndarray) and mp.size == 0):
            points_list.append(None)
        elif isinstance(mp, (tuple, list, np.ndarray)):
            points_list.append(tuple(mp))
        else:
            points_list.append(None)

    # 3. 🔧 批量提取 (优化版)
    sift_descriptors, success_mask = extractor.extract_batch(img_gray, points_list)

    return sift_descriptors, success_mask


# ================= 5. 批量处理 (保持不变,使用优化提取器) =================

def batch_extract_sift(image_folder: str, feature_folder: str, output_folder: str,
                       file_extensions: Optional[List[str]] = None,
                       start_idx: int = 0, end_idx: Optional[int] = None):
    """批量为文件夹中的图像提取 SIFT 特征 (使用优化版)"""
    if file_extensions is None:
        file_extensions = ['.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff']

    os.makedirs(output_folder, exist_ok=True)

    # 查找图像文件
    image_files = []
    for ext in file_extensions:
        image_files.extend(Path(image_folder).glob(f'*{ext}'))
        image_files.extend(Path(image_folder).glob(f'*{ext.upper()}'))
    image_files = list(set(image_files))
    image_files.sort()

    if end_idx is None:
        end_idx = len(image_files)
    image_files = image_files[start_idx:end_idx]

    if len(image_files) == 0:
        print(f"❌ 在 {image_folder} 中未找到图片文件")
        return None

    print("=" * 70)
    print(f"批量提取 SIFT 特征 (🚀 高性能优化版)")
    print(f"  图像文件夹:{image_folder}")
    print(f"  特征文件夹:{feature_folder}")
    print(f"  输出文件夹:{output_folder}")
    print(f"  图片数量:{len(image_files)}")
    print(f"  🔧 优化策略:")
    print(f"     • 整图预计算梯度 (避免 120× 重复)")
    print(f"     • 向量化直方图计算 (替代嵌套 for)")
    print(f"     • 预计算高斯权重模板")
    print(f"     • 批量处理关键点")
    print("=" * 70)

    # 🔧 初始化优化版提取器
    extractor = SIFTFeatureExtractorOptimized()

    results = []
    success_count = 0
    total_points = 0
    total_success = 0

    for i, image_path in enumerate(tqdm(image_files, desc="Processing")):
        base_name = image_path.stem
        matched_points_path = os.path.join(feature_folder, f'{base_name}{MATCHED_POINTS_FILE_SUFFIX}')

        if not os.path.exists(matched_points_path):
            print(f"\n[{i + 1}/{len(image_files)}] ⚠️  跳过 {base_name}: 无 matched_points 文件")
            continue

        print(f"\n[{i + 1}/{len(image_files)}] {base_name}")

        try:
            result = extract_sift_for_single_image(
                str(image_path), matched_points_path, extractor, output_folder
            )

            if result:
                results.append(result)
                success_count += 1

                report = result['report']
                total_points += report['n_points']
                total_success += report['success_count']

                print(f"  ✅ 提取完成:{report['success_count']}/{report['n_points']} 点成功 "
                      f"({report['success_rate'] * 100:.1f}%)")
            else:
                print(f"  ❌ 提取失败")

        except Exception as e:
            print(f"  ❌ 错误:{e}")
            import traceback
            traceback.print_exc()

    # 生成汇总报告
    overall_success_rate = total_success / total_points if total_points > 0 else 0.0

    summary = {
        'image_folder': str(image_folder),
        'feature_folder': str(feature_folder),
        'output_folder': str(output_folder),
        'total_images': len(image_files),
        'processed_images': success_count,
        'total_points': total_points,
        'total_success': total_success,
        'overall_success_rate': overall_success_rate,
        'optimization': 'precomputed_gradients_vectorized_histogram',
        'sift_config': {
            'patch_size': PATCH_SIZE,
            'grid_size': GRID_SIZE,
            'n_orientation_bins': N_ORIENTATION_BINS,
            'descriptor_dim': DESCRIPTOR_DIM,
            'padding_size': PADDING_SIZE
        },
        'results': []
    }

    for result in results:
        report = result['report']
        summary['results'].append({
            'image': Path(report['image_path']).name,
            'image_size': report['image_size'],
            'n_points': report['n_points'],
            'success_count': report['success_count'],
            'success_rate': report['success_rate']
        })

    summary_path = os.path.join(output_folder, 'batch_summary.json')
    with open(summary_path, 'w') as f:
        json.dump(summary, f, indent=2)

    print("\n" + "=" * 70)
    print(f"批量完成!")
    print(f"  处理图像:{success_count}/{len(image_files)}")
    print(f"  总坐标点:{total_points}")
    print(f"  成功提取:{total_success} ({overall_success_rate * 100:.1f}%)")
    print(f"  汇总报告:{summary_path}")
    print("=" * 70)

    return summary


# ================= 7. 主函数 =================

if __name__ == "__main__":
    import sys

    print("=" * 70)
    print("SIFT 特征提取系统 (🚀 高性能优化版)")
    print("优化:整图预计算梯度 + 向量化直方图 + 批量处理")
    print("=" * 70)

    mode = "single"  # 默认单图像测试

    if mode == 'extract':
        image_folder = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_IMAGE_FOLDER
        feature_folder = sys.argv[3] if len(sys.argv) > 3 else DEFAULT_FEATURE_FOLDER
        output_folder = sys.argv[4] if len(sys.argv) > 4 else DEFAULT_OUTPUT_FOLDER

        print(f"\n🔍 模式:批量提取 SIFT 特征")
        batch_extract_sift(image_folder, feature_folder, output_folder)

    elif mode == 'single':
        # 单图像测试
        image_path = "/path/to/circle_id/images/images/00059.png"
        matched_path = "/path/to/circle_id/outputs/polar_order/orignal_size/images/00059_matched_points.npy"
        output_path = "/path/to/circle_id/outputs/polar_order/temp/"

        print(f"\n🧪 模式:单图像测试")
        extractor = SIFTFeatureExtractorOptimized()

        start_time = time.time()
        # result = extract_sift_for_single_image(image_path, matched_path, extractor, output_path)

        # 1. 加载图像
        img = cv2.imread(image_path)
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) if len(img.shape) == 3 else img

        matched_points = np.load(matched_path, allow_pickle=True)
        sift_descriptors, mask = extract_sift_for_single_image_pure(img_gray, matched_points, extractor)
        print(sift_descriptors)
        print(mask)

        fig, ax = plt.subplots(1, 1, figsize=(12, 8))

        # 3. 显示图像
        ax.imshow(img)

        # 4. 在每个点上画圈
        for idx in range(len(matched_points.tolist())):
            # 方法1: 使用 Circle patch 画空心圆
            circle = plt.Circle(
                (matched_points[idx][0], matched_points[idx][1]),  # 圆心坐标
                radius=4,  # 半径
                fill=False,  # 不填充
                edgecolor='red',  # 边框颜色
                linewidth=3,  # 线宽
                linestyle='-'  # 实线 ('--'虚线, '-.'点划线)
            )
            ax.add_patch(circle)

        plt.tight_layout()
        plt.savefig("/path/to/circle_id/outputs/polar_order/temp/sift_features.png", dpi=150, bbox_inches='tight', pad_inches=0)
        plt.show()

        # 转换为列表格式
        elapsed = time.time() - start_time

        # if result:
        #     print(f"\n✅ 测试完成!耗时:{elapsed:.3f}s")
        #     print(f"  描述子形状:{result['descriptors'].shape}")
        #     print(f"  描述子维度:{DESCRIPTOR_DIM} 维")
        #     print(f"  成功点数:{result['report']['success_count']}/{result['report']['n_points']}")
        #     print(f"  平均速度:{result['report']['n_points'] / elapsed:.1f} 点/秒")