Download code/old/polar_order.py from qinxunhui/deepellipse-circleid: direct link, hf CLI and curl.
- Browser
- Download file 29.5 kB
-
https://huggingface.co/qinxunhui/deepellipse-circleid/resolve/main/code/old/polar_order.py
- Command line
-
hf download hf://qinxunhui/deepellipse-circleid/code/old/polar_order.py
-
curl -L -o polar_order.py https://huggingface.co/qinxunhui/deepellipse-circleid/resolve/main/code/old/polar_order.py
29.5 kB
| import os | |
| import string | |
| from datetime import time | |
| import random | |
| import cv2 | |
| import numpy | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| from skimage.morphology import skeletonize | |
| from pathlib import Path | |
| import json | |
| # ================= 配置参数 ================= | |
| # DEFAULT_INPUT = "/path/to/dataset/circle_id/images" | |
| # DEFAULT_INPUT = "/nas-02/hdd/public_datasets/icdar-2026-circleid-writer-identification/images/" | |
| # DEFAULT_OUTPUT = "/path/to/circle_id/circle_output/polar_order/orignal_size/images/" | |
| # DEFAULT_INPUT = "/nas-02/hdd/public_datasets/icdar-2026-circleid-writer-identification/ours_images/" | |
| # DEFAULT_OUTPUT = "/path/to/circle_id/circle_output/polar_order/orignal_size/ours_images/" | |
| DEFAULT_INPUT = "/path/to/circle_id/images/images/39557.png" | |
| DEFAULT_OUTPUT = "/path/to/circle_id/outputs/polar_order/temp/" | |
| N_SAMPLES = 120 | |
| ANGLE_TOLERANCE = 1.5 | |
| RADIUS_DIFF_THRESHOLD = 5.0 | |
| # ================= 1. 椭圆拟合 ================= | |
| def fit_ellipse_from_skeleton(skeleton_mask): | |
| """从骨架图像拟合椭圆""" | |
| points_y, points_x = np.where(skeleton_mask > 0) | |
| skeleton_points = np.column_stack((points_x, points_y)) | |
| if len(skeleton_points) < 5: | |
| print(f"二值图骨架异常,skeleton_points:{len(skeleton_points)}") | |
| return None, None | |
| contour = skeleton_points.reshape(-1, 1, 2).astype(np.float32) | |
| (cx, cy), (axis1, axis2), angle_raw = cv2.fitEllipse(contour) | |
| if axis1 >= axis2: | |
| MA, ma = axis1, axis2 | |
| angle = angle_raw | |
| else: | |
| MA, ma = axis2, axis1 | |
| angle = angle_raw + 90.0 | |
| if angle >= 180.0: | |
| angle -= 180.0 | |
| if MA < 30: | |
| # print(f"椭圆大小异常{MA}") | |
| return None, None | |
| a, b = MA / 2.0, ma / 2.0 | |
| angle_rad = np.radians(angle) | |
| cos_t, sin_t = np.cos(angle_rad), np.sin(angle_rad) | |
| errors = [] | |
| for x, y in skeleton_points: | |
| dx, dy = x - cx, y - cy | |
| x_rot = dx * cos_t + dy * sin_t | |
| y_rot = -dx * sin_t + dy * cos_t | |
| val = (x_rot ** 2 / a ** 2) + (y_rot ** 2 / b ** 2) | |
| if val > 0: | |
| err = abs(np.sqrt(val) - 1.0) * ((a + b) / 2.0) | |
| errors.append(err) | |
| fit_error = np.mean(errors) if errors else 0.0 | |
| ellipse_params = { | |
| 'cx': cx, 'cy': cy, | |
| 'MA': MA, 'ma': ma, | |
| 'a': a, 'b': b, | |
| 'angle': angle, 'angle_rad': angle_rad, | |
| 'fit_error': fit_error | |
| } | |
| return ellipse_params, skeleton_points | |
| # ================= 2. 极坐标转换 ================= | |
| def cartesian_to_polar(points, center): | |
| """将笛卡尔坐标转换为极坐标""" | |
| dx = points[:, 0] - center[0] | |
| dy = points[:, 1] - center[1] | |
| r = np.sqrt(dx ** 2 + dy ** 2) | |
| theta = np.degrees(np.arctan2(dy, dx)) | |
| theta = (theta + 360) % 360 | |
| return r, theta | |
| def polar_to_cartesian(r, theta_deg, center): | |
| """将极坐标转换回笛卡尔坐标""" | |
| theta_rad = np.radians(theta_deg) | |
| x = center[0] + r * np.cos(theta_rad) | |
| y = center[1] + r * np.sin(theta_rad) | |
| return np.array([x, y]) | |
| # ================= 3. 椭圆理论半径计算 ================= | |
| def ellipse_radius_at_angle(ellipse_params, theta_deg): | |
| """ | |
| 计算椭圆在指定几何角度下的理论半径(全局坐标系) | |
| 参数: | |
| ellipse_params: 椭圆参数字典 | |
| theta_deg: 全局坐标系下的角度(相对于图像 x 轴,0~360°) | |
| 返回: | |
| radius: 该角度下椭圆边界点到中心的距离(像素) | |
| """ | |
| a = ellipse_params['a'] # 长半轴 | |
| b = ellipse_params['b'] # 短半轴 | |
| angle_rad = ellipse_params['angle_rad'] # 长轴相对于全局 x 轴的角度 | |
| # 1. 将全局角度转换到椭圆局部坐标系(相对于长轴) | |
| theta_rad = np.radians(theta_deg) | |
| phi = theta_rad - angle_rad | |
| # 2. 椭圆极坐标方程(几何角度→半径) | |
| x_local = a * np.cos(phi) | |
| y_local = b * np.sin(phi) | |
| radius = np.sqrt(x_local ** 2 + y_local ** 2) | |
| return radius | |
| # ================= 4. 核心:120 维特征提取(优化版)================= | |
| def extract_polar_ordered_features(skeleton_mask, ellipse_params, n_samples=N_SAMPLES, | |
| angle_tolerance=ANGLE_TOLERANCE, | |
| radius_diff_threshold=RADIUS_DIFF_THRESHOLD): | |
| """ | |
| 🔧 优化版:逆时针采样 + 特征规范化 | |
| 改进: | |
| 1. 角度迭代:逆时针旋转 (angle + i*3) | |
| 2. 特征规范化:角度→弧度,半径→除以长半轴 a | |
| 3. 保留 matched_points 坐标 | |
| """ | |
| cx, cy = ellipse_params['cx'], ellipse_params['cy'] | |
| a = ellipse_params['a'] # 长半轴,用于半径归一化 | |
| # 1. 提取所有骨架点并转换为极坐标 | |
| points_y, points_x = np.where(skeleton_mask > 0) | |
| skeleton_points = np.column_stack((points_x, points_y)) | |
| # 转换为极坐标 | |
| r_vals, theta_vals = cartesian_to_polar(skeleton_points, (cx, cy)) | |
| features = [] | |
| matched_points = [] # 🔧 保留原始坐标 | |
| prev_point = None | |
| for i in range(n_samples): | |
| # 2. 🔧 计算当前采样角度(逆时针) | |
| t_theta_deg = (i * 360 / n_samples) % 360 | |
| t_r = ellipse_radius_at_angle(ellipse_params, t_theta_deg) | |
| # 🔧 规范化理论值 | |
| t_theta_rad = np.radians(t_theta_deg) | |
| t_r_norm = t_r / a | |
| # 3. 在容差范围内找候选点 | |
| theta_lower = (t_theta_deg - angle_tolerance + 360) % 360 | |
| theta_upper = (t_theta_deg + angle_tolerance) % 360 | |
| if theta_lower > theta_upper: | |
| mask = (theta_vals >= theta_lower) | (theta_vals <= theta_upper) | |
| else: | |
| mask = (theta_vals >= theta_lower) & (theta_vals <= theta_upper) | |
| candidate_indices = np.where(mask)[0] | |
| if len(candidate_indices) == 0: | |
| # 无匹配,填充规范化默认值 | |
| features.append(numpy.array([t_r_norm, t_theta_rad/6.283, 0, 0, t_r_norm, t_theta_rad/6.283, 0, 0])) | |
| matched_points.append(numpy.array([-1, -1])) | |
| continue | |
| # 提取候选点属性 | |
| candidate_r = r_vals[candidate_indices] | |
| candidate_theta = theta_vals[candidate_indices] | |
| candidate_points = skeleton_points[candidate_indices] | |
| # 计算角度差异 | |
| angle_diff = np.abs(candidate_theta - t_theta_deg) | |
| angle_diff = np.minimum(angle_diff, 360 - angle_diff) | |
| # 计算半径差异 | |
| radius_diff_to_theory = np.abs(candidate_r - t_r) | |
| # 找角度最接近的 2 个点 | |
| if len(candidate_indices) >= 2: | |
| top_2_local_idx = np.argsort(angle_diff)[:2] | |
| else: | |
| top_2_local_idx = np.array([0]) | |
| refined_r = candidate_r[top_2_local_idx] | |
| refined_theta = candidate_theta[top_2_local_idx] | |
| refined_angle_diff = angle_diff[top_2_local_idx] | |
| refined_radius_diff = radius_diff_to_theory[top_2_local_idx] | |
| refined_global_idx = candidate_indices[top_2_local_idx] | |
| # 根据半径差异阈值决定选择策略 | |
| if len(top_2_local_idx) >= 2: | |
| r1, r2 = refined_r[0], refined_r[1] | |
| radius_diff_between_candidates = abs(r1 - r2) | |
| if radius_diff_between_candidates < radius_diff_threshold: | |
| strategy = 0.5 # 角度优先 | |
| best_local_idx = np.argmin(refined_angle_diff) | |
| else: | |
| strategy = 1 # 半径优先 | |
| best_local_idx = np.argmin(refined_radius_diff) | |
| best_global_idx = refined_global_idx[best_local_idx] | |
| else: | |
| best_global_idx = candidate_indices[0] | |
| strategy = 0.5 | |
| # 获取最优匹配点 | |
| best_r = r_vals[best_global_idx] | |
| best_theta_deg = theta_vals[best_global_idx] | |
| best_point = skeleton_points[best_global_idx] # 🔧 保留原始 (x, y) 坐标 | |
| # 🔧 规范化实际值 | |
| best_r_norm = best_r / a | |
| best_theta_rad = np.radians(best_theta_deg) | |
| # 计算 dis(欧氏距离) todo | |
| dis = 0.0 | |
| # 误差计算 | |
| e_r_norm = t_r_norm - best_r_norm | |
| e_theta_rad = t_theta_rad - best_theta_rad | |
| # 🔧 特征格式(全部规范化): | |
| # (t_r_norm, t_theta_rad, r_norm, theta_rad, e_r_norm, e_theta_rad, dis, strategy) | |
| features.append(numpy.array([t_r_norm, t_theta_rad/6.283, best_r_norm, best_theta_rad/6.283, | |
| e_r_norm, e_theta_rad/6.283, dis, strategy])) | |
| matched_points.append(best_point.astype(int)) # 🔧 保留原始坐标 | |
| prev_point = best_point | |
| return numpy.array(features), numpy.array(matched_points) | |
| # ================= 5. 可视化(适配规范化特征)================= | |
| def visualize_polar_sampling( | |
| original_img, | |
| skeleton_mask, | |
| ellipse_params, | |
| features, | |
| matched_points, | |
| output_path='polar_sampling.png' | |
| ): | |
| """可视化极坐标采样结果(适配规范化特征)""" | |
| fig, axes = plt.subplots(1, 2, figsize=(18, 7)) | |
| cx, cy = ellipse_params['cx'], ellipse_params['cy'] | |
| a, b = ellipse_params['a'], ellipse_params['b'] | |
| angle = ellipse_params['angle'] | |
| angle_rad = ellipse_params['angle_rad'] | |
| # ========== 图 1: 原始图 + 椭圆 + 轴 + 采样点 ========== | |
| axes[0].imshow(cv2.cvtColor(original_img, cv2.COLOR_BGR2RGB)) | |
| axes[0].set_title('原始图像 + 椭圆拟合 + 采样点', fontsize=12) | |
| axes[0].axis('off') | |
| from matplotlib.patches import Ellipse | |
| ellipse = Ellipse( | |
| (cx, cy), ellipse_params['MA'], ellipse_params['ma'], | |
| angle=angle, | |
| fill=False, color='blue', linewidth=2, linestyle='--', | |
| label='拟合椭圆', alpha=0.7 | |
| ) | |
| axes[0].add_patch(ellipse) | |
| # 绘制椭圆中心 | |
| axes[0].scatter(cx, cy, c='red', s=100, marker='*', | |
| edgecolors='white', linewidths=2, | |
| label=f'中心 ({cx:.1f}, {cy:.1f})', zorder=10) | |
| # 绘制长轴和短轴 | |
| major_axis_end1 = (cx + a * np.cos(angle_rad), cy + a * np.sin(angle_rad)) | |
| major_axis_end2 = (cx - a * np.cos(angle_rad), cy - a * np.sin(angle_rad)) | |
| minor_axis_end1 = (cx - b * np.sin(angle_rad), cy + b * np.cos(angle_rad)) | |
| minor_axis_end2 = (cx + b * np.sin(angle_rad), cy - b * np.cos(angle_rad)) | |
| axes[0].plot([major_axis_end1[0], major_axis_end2[0]], | |
| [major_axis_end1[1], major_axis_end2[1]], | |
| 'r-', linewidth=2, label=f'长轴 ({ellipse_params["MA"]:.1f})', zorder=5) | |
| axes[0].plot([minor_axis_end1[0], minor_axis_end2[0]], | |
| [minor_axis_end1[1], minor_axis_end2[1]], | |
| 'g-', linewidth=2, label=f'短轴 ({ellipse_params["ma"]:.1f})', zorder=5) | |
| # 标注 theta=0 的角度(长轴方向) | |
| arrow_length = a * 0.8 | |
| arrow_end = (cx + arrow_length * np.cos(0), | |
| cy + arrow_length * np.sin(0)) | |
| axes[0].annotate('', xy=arrow_end, xytext=(cx, cy), | |
| arrowprops=dict(arrowstyle='->', color='orange', | |
| linewidth=3, ls='-')) | |
| axes[0].text(arrow_end[0] + 10, arrow_end[1], | |
| 'θ=0°', fontsize=10, color='orange', | |
| fontweight='bold', bbox=dict(facecolor='white', alpha=0.7)) | |
| # 绘制采样点(区分策略) | |
| angle_priority_count = 0 | |
| radius_priority_count = 0 | |
| missing_count = 0 | |
| for i, (t_r_norm, t_theta_rad, r_norm, theta_rad, e_r_norm, e_theta_rad, dis, strategy) in enumerate(features): | |
| # 🔧 反规范化用于可视化:弧度→度数,归一化半径→实际半径 | |
| t_theta_deg = np.degrees(t_theta_rad) | |
| t_r = t_r_norm * a | |
| t_point = polar_to_cartesian(t_r, t_theta_deg, (cx, cy)) | |
| if matched_points[i] is not None: | |
| if strategy == 1: | |
| axes[0].scatter(matched_points[i][0], matched_points[i][1], | |
| c='cyan', s=25, marker='o', | |
| edgecolors='white', linewidths=1, alpha=0.8) | |
| angle_priority_count += 1 | |
| elif strategy == 2: | |
| axes[0].scatter(matched_points[i][0], matched_points[i][1], | |
| c='yellow', s=25, marker='o', | |
| edgecolors='black', linewidths=1, alpha=0.8) | |
| radius_priority_count += 1 | |
| else: | |
| axes[0].scatter(t_point[0], t_point[1], | |
| c='red', s=25, marker='o', | |
| edgecolors='white', linewidths=1, alpha=0.8) | |
| missing_count += 1 | |
| legend_text = f'✅ 角度优先:{angle_priority_count}\n✅ 半径优先:{radius_priority_count}\n❌ 缺失:{missing_count}' | |
| axes[0].text(10, 30, legend_text, fontsize=10, | |
| bbox=dict(facecolor='white', alpha=0.9, edgecolor='black')) | |
| axes[0].legend(loc='upper right', fontsize=8) | |
| # ========== 图 2: 极坐标展开图 ========== | |
| axes[1].set_title('极坐标展开图 (顺时针 0°→360°)', fontsize=12) | |
| axes[1].set_xlabel('角度 (°)') | |
| axes[1].set_ylabel('归一化半径 (r/a)') | |
| axes[1].grid(alpha=0.3) | |
| # 理论椭圆半径曲线(归一化) | |
| angles_deg = np.linspace(0, 360, 360) | |
| theoretical_radii_norm = [ellipse_radius_at_angle(ellipse_params, ang) / a for ang in angles_deg] | |
| axes[1].plot(angles_deg, theoretical_radii_norm, 'b--', linewidth=1, | |
| label='理论椭圆半径 (归一化)', alpha=0.6) | |
| # 实际匹配点(区分策略,使用归一化值) | |
| angle_priority_angles = [] | |
| angle_priority_radii = [] | |
| radius_priority_angles = [] | |
| radius_priority_radii = [] | |
| missing_angles = [] | |
| missing_radii = [] | |
| for i, (t_r_norm, t_theta_rad, r_norm, theta_rad, e_r_norm, e_theta_rad, dis, strategy) in enumerate(features): | |
| theta_deg = np.degrees(theta_rad) | |
| if r_norm > 0: | |
| if strategy == 1: | |
| angle_priority_angles.append(theta_deg) | |
| angle_priority_radii.append(r_norm) | |
| elif strategy == 2: | |
| radius_priority_angles.append(theta_deg) | |
| radius_priority_radii.append(r_norm) | |
| else: | |
| missing_angles.append(np.degrees(t_theta_rad)) | |
| missing_radii.append(t_r_norm) | |
| if angle_priority_angles: | |
| axes[1].scatter(angle_priority_angles, angle_priority_radii, | |
| c='cyan', s=20, label='角度优先', alpha=0.7, edgecolors='black') | |
| if radius_priority_angles: | |
| axes[1].scatter(radius_priority_angles, radius_priority_radii, | |
| c='yellow', s=20, label='半径优先', alpha=0.7, edgecolors='black') | |
| if missing_angles: | |
| axes[1].scatter(missing_angles, missing_radii, | |
| c='red', s=20, label='缺失点', alpha=0.7, marker='x') | |
| axes[1].legend(loc='upper right', fontsize=9) | |
| axes[1].set_xlim(-10, 370) | |
| axes[1].set_ylim(0, 2.0) # 归一化半径范围 | |
| plt.tight_layout() | |
| plt.savefig(output_path, dpi=150, bbox_inches='tight') | |
| plt.close() | |
| print(f"✅ 可视化图像已保存:{output_path}") | |
| return output_path | |
| def visualize_feature_detail(features, output_path='feature_detail.png'): | |
| """可视化 120 维特征的详细信息(适配规范化特征)""" | |
| n_samples = len(features) | |
| # 🔧 提取规范化特征 | |
| t_r_norm_vals = [f[0] for f in features] | |
| t_theta_rad_vals = [f[1] for f in features] | |
| r_norm_vals = [f[2] for f in features] | |
| theta_rad_vals = [f[3] for f in features] | |
| dis_vals = [f[6] for f in features] | |
| strategy_vals = [f[7] for f in features] | |
| # 转换为度数用于绘图 | |
| t_theta_deg_vals = [np.degrees(t) for t in t_theta_rad_vals] | |
| theta_deg_vals = [np.degrees(t) for t in theta_rad_vals] | |
| fig, axes = plt.subplots(2, 2, figsize=(14, 10)) | |
| angle_priority_mask = [s == 1 for s in strategy_vals] | |
| radius_priority_mask = [s == 2 for s in strategy_vals] | |
| # 1. 理论半径 vs 实际半径(归一化) | |
| axes[0, 0].plot(t_theta_deg_vals, t_r_norm_vals, 'b--', linewidth=1, | |
| label='理论半径 (归一化)', alpha=0.6) | |
| if any(angle_priority_mask): | |
| axes[0, 0].scatter([t for i, t in enumerate(theta_deg_vals) if angle_priority_mask[i]], | |
| [r for i, r in enumerate(r_norm_vals) if angle_priority_mask[i]], | |
| c='cyan', s=15, label='角度优先', alpha=0.7, edgecolors='black') | |
| if any(radius_priority_mask): | |
| axes[0, 0].scatter([t for i, t in enumerate(theta_deg_vals) if radius_priority_mask[i]], | |
| [r for i, r in enumerate(r_norm_vals) if radius_priority_mask[i]], | |
| c='yellow', s=15, label='半径优先', alpha=0.7, edgecolors='black') | |
| axes[0, 0].set_xlabel('角度 (°)') | |
| axes[0, 0].set_ylabel('归一化半径 (r/a)') | |
| axes[0, 0].set_title('半径对比(归一化,区分选择策略)') | |
| axes[0, 0].legend(fontsize=8) | |
| axes[0, 0].grid(alpha=0.3) | |
| # 2. 半径误差(归一化) | |
| radius_errors = [abs(r - t) if r > 0 else t for t, r in zip(t_r_norm_vals, r_norm_vals)] | |
| axes[0, 1].bar(t_theta_deg_vals, radius_errors, width=2.5, color='orange', alpha=0.7) | |
| axes[0, 1].axhline(y=RADIUS_DIFF_THRESHOLD / 100, color='red', linestyle='--', | |
| label=f'阈值 (归一化)', alpha=0.6) | |
| axes[0, 1].set_xlabel('角度 (°)') | |
| axes[0, 1].set_ylabel('归一化半径误差') | |
| axes[0, 1].set_title('半径误差分布(归一化)') | |
| axes[0, 1].legend(fontsize=8) | |
| axes[0, 1].grid(alpha=0.3, axis='y') | |
| # # 3. 相邻点距离 dis | |
| # axes[1, 0].bar(t_theta_deg_vals, dis_vals, width=2.5, color='purple', alpha=0.7) | |
| # axes[1, 0].axhline(y=20, color='red', linestyle='--', label='阈值=20', alpha=0.6) | |
| # axes[1, 0].set_xlabel('角度 (°)') | |
| # axes[1, 0].set_ylabel('相邻点距离 (像素)') | |
| # axes[1, 0].set_title('相邻采样点欧氏距离') | |
| # axes[1, 0].legend(fontsize=8) | |
| # axes[1, 0].grid(alpha=0.3, axis='y') | |
| # 4. 特征统计 | |
| valid_count = sum(1 for r in r_norm_vals if r > 0) | |
| missing_count = n_samples - valid_count | |
| angle_priority_count = sum(1 for s in strategy_vals if s == 1) | |
| radius_priority_count = sum(1 for s in strategy_vals if s == 2) | |
| avg_error = np.mean([abs(r - t) for t, r in zip(t_r_norm_vals, r_norm_vals) if r > 0]) if valid_count > 0 else 0 | |
| max_dis = np.max(dis_vals) if dis_vals else 0 | |
| stats_text = f""" | |
| 采样总数:{n_samples} | |
| ✅ 角度优先:{angle_priority_count} ({angle_priority_count / n_samples * 100:.1f}%) | |
| ✅ 半径优先:{radius_priority_count} ({radius_priority_count / n_samples * 100:.1f}%) | |
| ❌ 缺失点:{missing_count} ({missing_count / n_samples * 100:.1f}%) | |
| 平均归一化误差:{avg_error:.4f} | |
| 最大相邻距离:{max_dis:.2f} 像素 | |
| """ | |
| axes[1, 1].axis('off') | |
| axes[1, 1].text(0.5, 0.5, stats_text, fontsize=11, | |
| ha='center', va='center', | |
| bbox=dict(facecolor='lightblue', alpha=0.3, boxstyle='round')) | |
| axes[1, 1].set_title('特征统计摘要(归一化)') | |
| plt.tight_layout() | |
| plt.savefig(output_path, dpi=150, bbox_inches='tight') | |
| plt.close() | |
| print(f"✅ 特征详情图已保存:{output_path}") | |
| return output_path | |
| # ================= 6. 单图像处理 ================= | |
| def process_single_image_polar(img, image_path=None, output_dir=None, visualize=False, n_samples=N_SAMPLES): | |
| """处理单张图像""" | |
| if image_path is not None: | |
| img = cv2.imread(image_path) | |
| base_name = Path(image_path).stem | |
| if img is None: | |
| print(f"❌ 无法读取图像:{image_path}") | |
| return None | |
| gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | |
| # blur = cv2.GaussianBlur(gray, (5, 5), 0) | |
| _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) | |
| skeleton_bool = skeletonize(binary // 255) | |
| skeleton_mask = (skeleton_bool * 255).astype(np.uint8) | |
| ellipse_params, skeleton_points = fit_ellipse_from_skeleton(skeleton_mask) | |
| if ellipse_params is None: | |
| # print(f"❌ 椭圆拟合失败:{image_path}") | |
| # length = 12 | |
| # random_str = ''.join(random.choices(string.ascii_letters + string.digits, k=length)) | |
| # cv2.imwrite(f"/path/to/circle_id/circle_output/augment2/fail_elipse_{random_str}.png", img) | |
| # cv2.imwrite(f"/path/to/circle_id/circle_output/augment2/fail_elipse_{random_str}_bin.png", binary) | |
| return None | |
| features, matched_points = extract_polar_ordered_features( | |
| skeleton_mask, ellipse_params, n_samples=n_samples | |
| ) | |
| if visualize: | |
| vis_path = os.path.join(output_dir, f'{base_name}_polar_sampling.png') | |
| visualize_polar_sampling(img, skeleton_mask, ellipse_params, features, matched_points, vis_path) | |
| detail_path = os.path.join(output_dir, f'{base_name}_feature_detail.png') | |
| visualize_feature_detail(features, detail_path) | |
| report = {} | |
| if output_dir is not None: | |
| # 🔧 保存特征(规范化格式) | |
| features_path = os.path.join(output_dir, f'{base_name}_features.npy') | |
| np.save(features_path, np.array(features, dtype=np.float32)) | |
| # 🔧 保存 matched_points 坐标 | |
| matched_path = os.path.join(output_dir, f'{base_name}_matched_points.npy') | |
| np.save(matched_path, np.array(matched_points, dtype=object)) | |
| report = { | |
| 'image_path': image_path, | |
| 'ellipse_params': { | |
| 'cx': float(ellipse_params['cx']), | |
| 'cy': float(ellipse_params['cy']), | |
| 'MA': float(ellipse_params['MA']), | |
| 'ma': float(ellipse_params['ma']), | |
| 'angle': float(ellipse_params['angle']), | |
| 'fit_error': float(ellipse_params['fit_error']) | |
| }, | |
| 'n_samples': n_samples, | |
| 'angle_tolerance': ANGLE_TOLERANCE, | |
| 'radius_diff_threshold': RADIUS_DIFF_THRESHOLD, | |
| 'matched_count': sum(1 for mp in matched_points if mp is not None), | |
| 'missing_count': sum(1 for mp in matched_points if mp is None), | |
| 'angle_priority_count': sum(1 for f in features if f[7] == 1), | |
| 'radius_priority_count': sum(1 for f in features if f[7] == 2), | |
| 'features_shape': [n_samples, 8], | |
| 'feature_names': ['t_r_norm', 't_theta_rad', 'r_norm', 'theta_rad', 'e_r_norm', 'e_theta_rad', 'dis', | |
| 'strategy'], | |
| 'feature_normalization': { | |
| 'radius': 'divided_by_semi_major_axis (a)', | |
| 'angle': 'degrees_to_radians' | |
| }, | |
| 'strategy_legend': {0: '无匹配', 1: '角度优先', 2: '半径优先'}, | |
| 'output_files': { | |
| 'features': features_path, | |
| 'matched_points': matched_path, # 🔧 新增 | |
| 'visualization': os.path.join(output_dir, f'{base_name}_polar_sampling.png') if visualize else None, | |
| 'detail': os.path.join(output_dir, f'{base_name}_feature_detail.png') if visualize else None | |
| } | |
| } | |
| report_path = os.path.join(output_dir, f'{base_name}_report.json') | |
| with open(report_path, 'w') as f: | |
| json.dump(report, f, indent=2) | |
| return { | |
| 'features': np.array(features, dtype=np.float32), #120*8的特征 | |
| 'matched_points': matched_points, # 🔧 返回原始坐标 | |
| 'ellipse_params': ellipse_params, | |
| 'report': report | |
| } | |
| # ================= 7. 批量处理文件夹 ================= | |
| def process_folder_polar(input_folder, output_folder, visualize=False, n_samples=N_SAMPLES, file_extensions=None): | |
| """批量处理文件夹""" | |
| 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(input_folder).glob(f'*{ext}')) | |
| image_files.extend(Path(input_folder).glob(f'*{ext.upper()}')) | |
| image_files = list(set(image_files)) | |
| image_files.sort() | |
| if len(image_files) == 0: | |
| print(f"❌ 在 {input_folder} 中未找到图片文件") | |
| return None | |
| print("=" * 70) | |
| print(f"批量处理:极坐标有序特征提取 (顺时针 + 规范化)") | |
| print(f" 输入:{input_folder}") | |
| print(f" 输出:{output_folder}") | |
| print(f" 图片数:{len(image_files)}") | |
| print(f" 采样数:{n_samples} (每 {360 / n_samples}°, 顺时针)") | |
| print(f" 角度容差:±{ANGLE_TOLERANCE}°") | |
| print(f" 半径差异阈值:{RADIUS_DIFF_THRESHOLD} 像素") | |
| print(f" 特征规范化:角度→弧度,半径→除以长半轴") | |
| print("=" * 70) | |
| results = [] | |
| success_count = 0 | |
| for i, image_path in enumerate(image_files): | |
| print(f"\n[{i + 1}/{len(image_files)}] {image_path.name}") | |
| try: | |
| result = process_single_image_polar(str(image_path), output_folder, visualize, n_samples) | |
| if result: | |
| results.append(result) | |
| success_count += 1 | |
| report = result['report'] | |
| print(f" ✅ 椭圆:MA={report['ellipse_params']['MA']:.1f}, " | |
| f"ma={report['ellipse_params']['ma']:.1f}, " | |
| f"误差={report['ellipse_params']['fit_error']:.2f}") | |
| print(f" 📊 匹配:{report['matched_count']}/{n_samples} " | |
| f"({report['matched_count'] / n_samples * 100:.1f}%)") | |
| print(f" 角度优先:{report['angle_priority_count']}, " | |
| f"半径优先:{report['radius_priority_count']}") | |
| else: | |
| print(f" ❌ 处理失败") | |
| except Exception as e: | |
| print(f" ❌ 错误:{e}") | |
| import traceback | |
| traceback.print_exc() | |
| summary = { | |
| 'input_folder': str(input_folder), | |
| 'output_folder': str(output_folder), | |
| 'total_images': len(image_files), | |
| 'success_count': success_count, | |
| 'success_rate': success_count / len(image_files) if len(image_files) > 0 else 0.0, | |
| 'n_samples': n_samples, | |
| 'angle_tolerance': ANGLE_TOLERANCE, | |
| 'radius_diff_threshold': RADIUS_DIFF_THRESHOLD, | |
| 'normalization': { | |
| 'radius': 'divided_by_semi_major_axis', | |
| 'angle': 'degrees_to_radians' | |
| }, | |
| 'results': [] | |
| } | |
| for result in results: | |
| report = result['report'] | |
| summary['results'].append({ | |
| 'image': Path(report['image_path']).name, | |
| 'ellipse': report['ellipse_params'], | |
| 'matched_count': report['matched_count'], | |
| 'missing_count': report['missing_count'], | |
| 'angle_priority_count': report['angle_priority_count'], | |
| 'radius_priority_count': report['radius_priority_count'] | |
| }) | |
| 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"批量完成!成功 {success_count}/{len(image_files)}") | |
| print(f"汇总报告:{summary_path}") | |
| print("=" * 70) | |
| return summary | |
| # ================= 8. 主函数 ================= | |
| if __name__ == "__main__": | |
| import sys | |
| print("=" * 70) | |
| print("极坐标有序特征提取系统 v3.0") | |
| print("优化:顺时针采样 + 特征规范化 (角度→弧度,半径→r/a) + 保留 matched_points") | |
| print("=" * 70) | |
| if len(sys.argv) > 1: | |
| input_path = sys.argv[1] | |
| else: | |
| input_path = DEFAULT_INPUT | |
| if len(sys.argv) > 2: | |
| output_folder = sys.argv[2] | |
| else: | |
| output_folder = DEFAULT_OUTPUT | |
| if os.path.isfile(input_path): | |
| print(f"\n📷 单图像模式:{input_path}") | |
| os.makedirs(output_folder, exist_ok=True) | |
| result = process_single_image_polar(input_path, output_folder, visualize=False) | |
| if result: | |
| features = result['features'] | |
| print(f"\n✅ 特征提取完成!") | |
| print(f" 特征维度:{features.shape}") | |
| print( | |
| f" 特征字段:['t_r_norm', 't_theta_rad', 'r_norm', 'theta_rad', 'e_r_norm', 'e_theta_rad', 'dis', 'strategy']") | |
| print(f" 规范化:角度→弧度,半径→除以长半轴 (a)") | |
| print(f" 匹配率:{result['report']['matched_count']}/120") | |
| print(f" matched_points 坐标已保存") | |
| else: | |
| print("\n❌ 处理失败") | |
| elif os.path.isdir(input_path): | |
| print(f"\n📁 批量文件夹模式:{input_path}") | |
| summary = process_folder_polar(input_path, output_folder, visualize=False) | |
| if summary: | |
| print(f"\n✅ 批量完成!成功 {summary['success_count']}/{summary['total_images']}") | |
| else: | |
| print(f"❌ 路径不存在:{input_path}") | |
| print("\n使用方法:") | |
| print(" python polar_order.py # 默认文件夹") | |
| print(" python polar_order.py /path/to/images # 指定输入") | |
| print(" python polar_order.py image.png # 单张图像") | |
| print(" python polar_order.py /in /out # 指定输入输出") |