File size: 13,890 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
import os
import cv2
import numpy as np
from pathlib import Path
import random

from circle_feature import exact_features
from color_aug_class import ColorStatsDatabase, CircleColorAugmentor
from image_precess import estimate_stroke_width
import traceback

DEF_PROB_DICT = {"crop": 0.3,
                 "rotation": 0.5,
                 "shear": 0.3,
                 "affine": 0.5,
                 "stroke": 0.3,
                 "color": 0.5,
                 "blur": 0.3
                 }

# DEF_PROB_DICT = {"crop": 1,
#                  "rotation": 1,
#                  "shear": 1,
#                  "affine": 1,
#                  "stroke": 1,
#                  "color": 1,
#                  "blur": 1
#                  }

# ================= 核心增强类 (带调试记录) =================
class CircleAugmentation:
    def __init__(
            self,
            color_cache_file=os.path.join(os.path.dirname(__file__), "test_color_sta.json"),
            prob_dict=DEF_PROB_DICT,
    ):
        # 记录每一步的图像
        self.steps = {}
        ref_db = ColorStatsDatabase(color_cache_file)
        self.color_augmentor = CircleColorAugmentor(ref_db, match_std=True)
        self.prob_dict = prob_dict

    def apply_crop(self, image):
        """步骤 1: 随机单方向边缘裁剪 (20% 概率)"""
        h, w = image.shape[:2]
        step_name = "1_Crop"

        if random.random() > self.prob_dict["crop"]:
            # 不发生裁剪,直接返回原图副本
            self.steps[step_name] = image.copy()
            self.steps[f"{step_name}_info"] = "No Crop"
            return image

        # 决定裁剪方向:0:Top, 1:Bottom, 2:Left, 3:Right
        direction = random.randint(0, 3)
        max_pixels = int(min(h, w) * 0.2)
        crop_amount = random.randint(1, max_pixels)

        y1, y2, x1, x2 = 0, h, 0, w

        if direction == 0:  # Top
            y1 = crop_amount
            info = f"Top-{crop_amount}px"
        elif direction == 1:  # Bottom
            y2 = h - crop_amount
            info = f"Bottom-{crop_amount}px"
        elif direction == 2:  # Left
            x1 = crop_amount
            info = f"Left-{crop_amount}px"
        else:  # Right
            x2 = w - crop_amount
            info = f"Right-{crop_amount}px"

        cropped = image[y1:y2, x1:x2].copy()
        self.steps[step_name] = cropped
        self.steps[f"{step_name}_info"] = info
        return cropped

    def apply_rotation(self, image, degrees=20):
        step_name = "rotation"
        if random.random() > self.prob_dict["rotation"]:
            # 不发生裁剪,直接返回原图副本
            self.steps[step_name] = image.copy()
            self.steps[f"{step_name}_info"] = "No " + step_name
            return image

        """步骤 2: 随机旋转"""
        h, w = image.shape[:2]
        center = (w // 2, h // 2)
        angle = np.random.uniform(-degrees, degrees)
        M = cv2.getRotationMatrix2D(center, angle, 1.0)
        rotated = cv2.warpAffine(image, M, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255), flags=cv2.INTER_LINEAR)

        self.steps["2_Rotate"] = rotated
        self.steps["2_Rotate_info"] = f"rotate:{angle:.1f}"
        return rotated

    def apply_shear(self, image, degrees=10):
        """步骤 3: 随机剪切"""
        step_name = "shear"
        if random.random() > self.prob_dict["shear"]:
            # 不发生裁剪,直接返回原图副本
            self.steps[step_name] = image.copy()
            self.steps[f"{step_name}_info"] = "No " + step_name
            return image

        h, w = image.shape[:2]
        shear_x = np.random.uniform(-np.tan(np.radians(degrees)), np.tan(np.radians(degrees)))
        shear_y = np.random.uniform(-np.tan(np.radians(degrees)), np.tan(np.radians(degrees)))
        M = np.float32([[1, shear_x, 0], [shear_y, 1, 0]])
        sheared = cv2.warpAffine(
            image,
            M,
            (w, h),
            borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255),
            flags=cv2.INTER_LINEAR
        )

        self.steps["3_Shear"] = sheared
        self.steps["3_Shear_info"] = f"sheer-x:{shear_x:.2f}, y:{shear_y:.2f}"
        return sheared

    def apply_affine(self, image, translate=(0.05, 0.05), scale=(0.95, 1.05)):
        """步骤 4: 随机平移 + 缩放"""
        step_name = "affine"
        if random.random() > self.prob_dict["affine"]:
            # 不发生裁剪,直接返回原图副本
            self.steps[step_name] = image.copy()
            self.steps[f"{step_name}_info"] = "No " + step_name
            return image

        h, w = image.shape[:2]
        tx = np.random.uniform(-translate[0], translate[0]) * w
        ty = np.random.uniform(-translate[1], translate[1]) * h
        sx = np.random.uniform(scale[0], scale[1])
        sy = np.random.uniform(scale[0], scale[1])

        M = np.float32([[sx, 0, tx], [0, sy, ty]])
        affine = cv2.warpAffine(image, M, (w, h), borderMode=cv2.BORDER_CONSTANT, borderValue=(255, 255, 255))

        self.steps["4_Affine"] = affine
        self.steps["4_Affine_info"] = f"affine aug"
        return affine

    def apply_stroke_aug(self, image):
        """步骤 5: 外观变换 (笔迹粗细)"""
        if random.random() > self.prob_dict["stroke"]:
            self.steps["5_Stroke"] = image.copy()
            self.steps["5_Stroke_info"] = "No stroke aug"
            return image

        # 模拟动态逻辑 (这里简化为随机变粗或变细,实际可接入 width 估算)
        kernel = np.ones((3, 3), np.uint8)
        width = estimate_stroke_width(image)
        if width > 6.5:
            op_type = -1
            # iter = random.randint(1, min(2, int((width - 3)/2)))
        else:
            op_type = 1
            # iter = random.randint(1, min(2, int((7.5 - width)/2)))
        iter = 1

        if len(image.shape) == 3:
            channels = cv2.split(image)
            new_ch = []

            for ch in channels:
                if op_type == -1:
                    mod = cv2.dilate(ch, kernel, iterations=iter)  #白色膨胀,笔画变细
                else:
                    mod = cv2.erode(ch, kernel, iterations=iter)  #白色腐蚀,笔画变粗
                new_ch.append(mod)
            result = cv2.merge(new_ch)

        self.steps["5_Stroke"] = result

        if op_type == -1:
            self.steps["5_Stroke_info"] = "small:" + f"w:{width:.1f}"
        else:
            self.steps["5_Stroke_info"] = "large:" + f"w:{width:.1f}"
        return result

    def apply_color(self, image, use_prob=0.5):
        """步骤 5: 外观变换 (笔迹粗细)"""
        if random.random() > use_prob:
            self.steps["6_colar"] = image.copy()
            self.steps["6_colar_info"] = "No color aug"
            return image
        image = self.color_augmentor.augment(image, b_debug=False)
        self.steps["6_colar"] = image
        self.steps["6_colar_info"] = "color aug"
        return image

    def apply_blur(self, image):
        """步骤 X: 外观变换 (图像模糊)"""
        # 1. 概率控制:只有 use_prob (默认 30%) 的概率发生模糊
        if random.random() > self.prob_dict["blur"]:
            self.steps["7_Blur"] = image.copy()
            self.steps["7_Blur_info"] = "No blur"
            return image

        ksize = random.choice([3, 5, 7])
        blurred_image = cv2.GaussianBlur(image, (ksize, ksize), 0)

        # 4. 记录调试信息
        self.steps["7_Blur"] = blurred_image
        self.steps["7_Blur_info"] = f"Gauss K={ksize}"

        return blurred_image

    def aug_image(self, image):
        """执行全流程并记录每一步"""
        # 0. Original
        self.steps["0_Original"] = image.copy()
        self.steps["0_Original_info"] = "Input"

        # 1. Crop
        img = self.apply_crop(image)
        # 2. Rotate
        img = self.apply_rotation(img)
        # 3. Shear
        img = self.apply_shear(img)
        # 4. Affine
        img = self.apply_affine(img)
        # 5. Stroke Aug
        img = self.apply_stroke_aug(img)
        # 6. color
        img = self.apply_color(img)
        # 7. blur
        img = self.apply_blur(img)

        return img


    def aug_image_offical(self, img):
        """执行全流程并记录每一步"""
        # 0. Original
        self.steps["0_Original"] = img.copy()
        self.steps["0_Original_info"] = "Input"

        # 1. Crop
        # img = self.apply_crop(image)
        # 2. Rotate
        img = self.apply_rotation(img)
        # 3. Shear
        # img = self.apply_shear(img)
        # 4. Affine
        img = self.apply_affine(img)
        # 5. Stroke Aug
        # img = self.apply_stroke_aug(img)
        # # 6. color
        # img = self.apply_color(img)
        # # 7. blur
        # img = self.apply_blur(img)

        return img

    def process_full_pipeline(self, image):
        """执行全流程并记录每一步"""
        # 0. Original
        self.steps["0_Original"] = image.copy()
        self.steps["0_Original_info"] = "Input"

        # 1. Crop
        img = self.apply_crop(image)
        # 2. Rotate
        img = self.apply_rotation(img)
        # 3. Shear
        img = self.apply_shear(img)
        # 4. Affine
        img = self.apply_affine(img)
        # 5. Stroke Aug
        img = self.apply_stroke_aug(img)
        # 6. color
        img = self.apply_color(img)
        # 7. blur
        img = self.apply_blur(img)

        return self.steps


# ================= 可视化工具 =================
def create_debug_image(steps, target_h=120):
    """将 steps 字典中的图像拼接成一行"""
    row_images = []

    # 定义显示顺序
    order = [
        "0_Original", "1_Crop", "2_Rotate", "3_Shear",
        "4_Affine", "5_Stroke", "6_colar", "7_Blur"
    ]

    for key in order:
        if key not in steps:
            continue

        img = steps[key]
        info = steps.get(f"{key}_info", "")

        # 统一高度
        h, w = img.shape[:2]
        if h != target_h:
            scale = target_h / h
            new_w = int(w * scale)
            img_resized = cv2.resize(img, (new_w, target_h))
        else:
            img_resized = img.copy()

        # 添加底部文字标签
        cv2.putText(img_resized, info, (5, target_h - 5),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0), 1)

        # 添加顶部标题 (简单用颜色条区分,或者只在第一张写)
        if key == "0_Original":
            cv2.putText(img_resized, "Original", (5, 15),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)

        row_images.append(img_resized)

    if not row_images:
        return None

    return np.hstack(row_images)


# ================= 主执行逻辑 =================
def debug_main():
    INPUT_FOLDER = "/path/to/circle_id/images/images/"
    OUTPUT_FOLDER = "/path/to/circle_id/outputs/augment2"

    FILE_PATTERN = "*.png"  # 或者 "*.png" 处理所有
    NUM_SAMPLES = 100  # 调试几张图片

    os.makedirs(OUTPUT_FOLDER, exist_ok=True)
    print(f"✅ 输出目录:{OUTPUT_FOLDER}")
    img_paths = list(Path(INPUT_FOLDER).glob(FILE_PATTERN))[:NUM_SAMPLES]
    print(f"🔍 找到 {len(img_paths)} 张图片,开始生成调试图...")

    aug = CircleAugmentation()

    for idx, path in enumerate(img_paths):
        # path = "/path/to/circle_id/images/images/10542.png"
        # path = "/path/to/circle_id/images/images/14406.png"
        # path = "/path/to/circle_id/images/images/21070.png"
        # path = "/path/to/circle_id/images/images/30164.png"
        #
        # path = "/path/to/circle_id/images/images/38334.png"
        # path = "/path/to/circle_id/images/images/39022.png"
        path = "/path/to/circle_id/images/images/39890.png"
        path_name = path.split("/")[-1]
        # path_name = path.name

        image = cv2.imread(str(path))
        if image is None:
            continue
        all_rows = []
        # 初始化增强器 (每次循环重新初始化以重置随机状态记录)

        # 执行流程
        steps = aug.process_full_pipeline(image)

        # 生成拼接图
        row_imgs = create_debug_image(steps, target_h=150)
        if row_imgs is not None:
            # 添加左侧文件名标签
            h, w, _ = row_imgs.shape
            label_img = np.ones((h, 150, 3), dtype=np.uint8) * 255
            cv2.putText(label_img, path_name, (10, h // 2),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 1)
            final_row = np.hstack([label_img, row_imgs])
            all_rows.append(final_row)

            # 垂直拼接所有行
            # 确保宽度一致 (取最小宽度)
            min_w = min([r.shape[1] for r in all_rows])
            padded_rows = []
            for r in all_rows:
                if r.shape[1] > min_w:
                    r = r[:, :min_w, :]
                padded_rows.append(r)

            final_grid = np.vstack(padded_rows)

            image_name = str(path).split("/")[-1]
            output_path = os.path.join(OUTPUT_FOLDER, f"{idx}_{image_name}")

            try:
                feature = exact_features(steps["7_Blur"])
            except Exception as e:
                print(steps["7_Blur"].shape)
                cv2.imwrite(output_path, final_grid)
                print(f"\n🎉 错误调试图已保存:{output_path}")
                print(str(path))
                print(traceback.format_exc())

if __name__ == "__main__":
    debug_main()
    # src_path = "/path/to/circle_id/images/images/00151.png"
    # img = cv2.imread(src_path)
    # aug = CircleAugmentation()
    # img_aug = aug.aug_image(img)
    # cv2.imwrite("/path/to/circle_id/outputs/polar_order/temp/00151.png", img_aug)
    # feature = exact_features(img_aug)