-
Notifications
You must be signed in to change notification settings - Fork 342
Expand file tree
/
Copy pathbasic_shape_processor.py
More file actions
1780 lines (1436 loc) · 65.9 KB
/
basic_shape_processor.py
File metadata and controls
1780 lines (1436 loc) · 65.9 KB
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
"""
任务3:基本图形处理模块
功能:
- 处理rectangle、ellipse、diamond等基本图形
- 从图片中提取填充色和描边色
- 检测边框宽度
- 用XML描述这些图形
- 支持CV补充检测(检测SAM3遗漏的矩形/容器)
- 输出XML片段
负责人:[已实现]
负责任务:任务3 - 基本图形类(取色,用XML描述)
使用示例:
from modules import BasicShapeProcessor, ProcessingContext
processor = BasicShapeProcessor()
context = ProcessingContext(image_path="test.png")
context.elements = [...] # 从SAM3获取的元素
result = processor.process(context)
# 处理后的元素会包含 fill_color, stroke_color, xml_fragment 字段
接口说明:
输入:
- context.elements: ElementInfo列表,筛选出基本图形
- context.image_path: 原始图片路径,用于取色
输出:
- 更新 element.fill_color: 填充颜色(十六进制)
- 更新 element.stroke_color: 描边颜色(十六进制)
- 更新 element.stroke_width: 描边宽度
- 更新 element.xml_fragment: 该元素的XML片段
"""
import os
import cv2
import numpy as np
import math
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
from typing import List, Tuple, Optional, Dict, Any
from PIL import Image
from .base import BaseProcessor, ProcessingContext
from .data_types import ElementInfo, BoundingBox, ProcessingResult, LayerLevel, get_layer_level
# ======================== DrawIO样式配置 ========================
DRAWIO_STYLES = {
"rectangle": "rounded=0;whiteSpace=wrap;html=1;",
"rounded rectangle": "rounded=1;whiteSpace=wrap;html=1;",
"title_bar": "rounded=0;whiteSpace=wrap;html=1;fillColor=#E6E6E6;",
"section_panel": "rounded=0;whiteSpace=wrap;html=1;dashed=1;dashPattern=1 1;",
"container": "rounded=1;whiteSpace=wrap;html=1;",
"diamond": "rhombus;whiteSpace=wrap;html=1;",
"ellipse": "ellipse;whiteSpace=wrap;html=1;",
"circle": "ellipse;whiteSpace=wrap;html=1;",
"cylinder": "shape=cylinder3;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;size=15;",
"cloud": "ellipse;shape=cloud;whiteSpace=wrap;html=1;",
"actor": "shape=umlActor;verticalLabelPosition=bottom;verticalAlign=top;html=1;outlineConnect=0;",
"hexagon": "shape=hexagon;perimeter=hexagonPerimeter2;whiteSpace=wrap;html=1;fixedSize=1;",
"triangle": "triangle;whiteSpace=wrap;html=1;",
"parallelogram": "shape=parallelogram;perimeter=parallelogramPerimeter;whiteSpace=wrap;html=1;fixedSize=1;",
"trapezoid": "shape=trapezoid;perimeter=trapezoidPerimeter;whiteSpace=wrap;html=1;fixedSize=1;",
"square": "rounded=0;whiteSpace=wrap;html=1;aspect=fixed;",
}
# 支持矢量化的图形类型
VECTOR_TYPES = {
"rectangle", "rounded_rectangle", "rounded rectangle",
"diamond", "ellipse", "circle",
"cylinder", "cloud", "actor",
"hexagon", "triangle", "parallelogram",
"title_bar", "section_panel", "container",
"trapezoid", "square"
}
# ======================== 几何参数提取 ========================
def extract_geometric_params(image: np.ndarray, bbox: list, shape_type: str) -> dict:
"""
针对特定形状提取几何参数(如平行四边形的倾斜度、圆柱体的顶部高度等)。
返回参数字典,例如 {"size": 0.2, "direction": "south"}
"""
params = {}
x1, y1, x2, y2 = map(int, bbox)
w_box, h_box = x2 - x1, y2 - y1
if w_box <= 0 or h_box <= 0:
return params
# 提取 ROI 用于分析
roi = image[y1:y2, x1:x2]
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
# 通用预处理:获取轮廓
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
main_cnt = None
max_area = 0
for cnt in contours:
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
main_cnt = cnt
if main_cnt is None:
return params
# 针对不同形状的分析
if shape_type == "parallelogram":
# 计算倾斜比例 size (0~1)
epsilon = 0.02 * cv2.arcLength(main_cnt, True)
approx = cv2.approxPolyDP(main_cnt, epsilon, True)
if len(approx) == 4:
pts = approx.reshape(4, 2)
pts = pts[np.argsort(pts[:, 1])]
top_pts = pts[:2]
bottom_pts = pts[2:]
top_pts = top_pts[np.argsort(top_pts[:, 0])]
bottom_pts = bottom_pts[np.argsort(bottom_pts[:, 0])]
tl, tr = top_pts[0], top_pts[1]
bl, br = bottom_pts[0], bottom_pts[1]
dx = abs(tl[0] - bl[0])
size_val = dx / w_box if w_box > 0 else 0.2
params["size"] = max(0.05, min(0.5, size_val))
elif shape_type == "cylinder":
params["size"] = max(10, int(w_box * 0.15))
elif shape_type == "triangle":
epsilon = 0.04 * cv2.arcLength(main_cnt, True)
approx = cv2.approxPolyDP(main_cnt, epsilon, True)
if len(approx) == 3:
M = cv2.moments(main_cnt)
if M["m00"] != 0:
cy = int(M["m01"] / M["m00"])
rel_cy = cy / h_box
if rel_cy > 0.55:
params["direction"] = "north"
elif rel_cy < 0.45:
params["direction"] = "south"
else:
cx = int(M["m10"] / M["m00"])
rel_cx = cx / w_box
if rel_cx > 0.55:
params["direction"] = "west"
elif rel_cx < 0.45:
params["direction"] = "east"
return params
# ======================== IoU计算 ========================
def calculate_iou(box1: list, box2: list) -> float:
"""计算两个矩形框的 IoU"""
x_left = max(box1[0], box2[0])
y_top = max(box1[1], box2[1])
x_right = min(box1[2], box2[2])
y_bottom = min(box1[3], box2[3])
if x_right < x_left or y_bottom < y_top:
return 0.0
intersection_area = (x_right - x_left) * (y_bottom - y_top)
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
union_area = box1_area + box2_area - intersection_area
if union_area <= 0:
return 0.0
return intersection_area / union_area
# ======================== 边框宽度检测 ========================
def calculate_stroke_width(image: np.ndarray, bbox: list, max_width: int = 8) -> int:
"""
计算边框粗细 (Stroke Width)
逻辑:沿四边向内扫描,寻找颜色突变点,多个采样点综合取中位数。
优化:
- 提高突变阈值(35),减少误检
- 限制最大宽度(8像素),避免过粗
- 大多数边框在 1-5 像素
"""
x1, y1, x2, y2 = map(int, bbox)
h, w = image.shape[:2]
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(w, x2), min(h, y2)
roi = image[y1:y2, x1:x2]
if roi.size == 0:
return 1
roi_h, roi_w = roi.shape[:2]
roi_gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
scan_limit = min(max_width, roi_w // 2 - 1, roi_h // 2 - 1)
if scan_limit < 1:
return 1
detected_widths = []
def scan_line(pixels, limit):
if len(pixels) < limit + 1:
return None
diffs = np.abs(np.diff(pixels[:limit+2].astype(int)))
threshold = 35 # 提高阈值,减少误检(原值20太敏感)
candidates = np.where(diffs > threshold)[0]
if len(candidates) > 0:
return candidates[0] + 1
return None
num_samples = 5
# Top Edge
for i in range(1, num_samples + 1):
x = int(roi_w * i / (num_samples + 1))
col = roi_gray[:, x]
w_val = scan_line(col, scan_limit)
if w_val:
detected_widths.append(w_val)
# Bottom Edge
for i in range(1, num_samples + 1):
x = int(roi_w * i / (num_samples + 1))
col = roi_gray[::-1, x]
w_val = scan_line(col, scan_limit)
if w_val:
detected_widths.append(w_val)
# Left Edge
for i in range(1, num_samples + 1):
y = int(roi_h * i / (num_samples + 1))
row = roi_gray[y, :]
w_val = scan_line(row, scan_limit)
if w_val:
detected_widths.append(w_val)
# Right Edge
for i in range(1, num_samples + 1):
y = int(roi_h * i / (num_samples + 1))
row = roi_gray[y, ::-1]
w_val = scan_line(row, scan_limit)
if w_val:
detected_widths.append(w_val)
if not detected_widths:
return 1
final_width = int(np.median(detected_widths))
# 限制合理范围:大多数边框在 1-2 像素(降低上限以匹配原图)
return max(1, min(final_width, 2))
# ======================== 颜色提取 ========================
def extract_style_colors(image: np.ndarray, bbox: list) -> tuple:
"""
精细化取色逻辑:区分 边框区域(Stroke) 和 内部区域(Fill)
优化策略:
1. Fill: 采样边框内侧的"回"字形区域(避开中心可能的文字),使用K-Means聚类找主色
2. Stroke: 提取边界框外围10%区域,取最暗的25%像素的均值作为边框色
3. 同时返回检测到的边框宽度
:param image: BGR格式的OpenCV图像
:param bbox: [x1, y1, x2, y2]
:return: (fill_color_hex, stroke_color_hex, stroke_width)
"""
x1, y1, x2, y2 = map(int, bbox)
h_box, w_box = y2 - y1, x2 - x1
# 截取ROI
roi = image[y1:y2, x1:x2]
if roi.size == 0:
return "#ffffff", "#000000", 1
roi_rgb = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
# --- 0. 检测边框宽度 ---
max_w = min(15, w_box // 5, h_box // 5)
stroke_width = calculate_stroke_width(image, bbox, max_width=max(1, max_w))
# --- 1. 提取填充色 (Fill Color) ---
# 优化:采样边框内侧的"回"字形区域,避开中心可能存在的文字
s_w = int(stroke_width)
border_padding = max(2, s_w + 2)
sample_depth = max(5, min(20, w_box // 10, h_box // 10))
fill_samples = []
if w_box > 2 * (border_padding + sample_depth) and h_box > 2 * (border_padding + sample_depth):
# Top strip (边框内侧上方)
fill_samples.append(roi_rgb[border_padding:border_padding+sample_depth, border_padding:w_box-border_padding])
# Bottom strip (边框内侧下方)
fill_samples.append(roi_rgb[h_box-border_padding-sample_depth:h_box-border_padding, border_padding:w_box-border_padding])
# Left strip (边框内侧左侧)
fill_samples.append(roi_rgb[border_padding:h_box-border_padding, border_padding:border_padding+sample_depth])
# Right strip (边框内侧右侧)
fill_samples.append(roi_rgb[border_padding:h_box-border_padding, w_box-border_padding-sample_depth:w_box-border_padding])
else:
# Fallback: 区域太小,取中心区域
margin_x = min(int(stroke_width + 2), w_box // 2 - 1)
margin_y = min(int(stroke_width + 2), h_box // 2 - 1)
if margin_x > 0 and margin_y > 0:
fill_samples.append(roi_rgb[margin_y:h_box-margin_y, margin_x:w_box-margin_x])
else:
fill_samples.append(roi_rgb)
# 合并所有采样像素
if fill_samples:
valid_samples = [s.reshape(-1, 3) for s in fill_samples if s.size > 0]
if valid_samples:
inner_pixels = np.concatenate(valid_samples)
else:
inner_pixels = roi_rgb.reshape(-1, 3)
else:
inner_pixels = roi_rgb.reshape(-1, 3)
if inner_pixels.size == 0:
inner_pixels = roi_rgb.reshape(-1, 3)
# 使用K-Means聚类找主色(比中位数更准确)
fill_rgb = np.median(inner_pixels, axis=0).astype(int) # 默认用中位数
if len(inner_pixels) > 200:
try:
# 降采样以提高速度
if len(inner_pixels) > 2000:
indices = np.random.choice(len(inner_pixels), 2000, replace=False)
pixels_for_kmeans = inner_pixels[indices].astype(np.float32)
else:
pixels_for_kmeans = inner_pixels.astype(np.float32)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
k = 2 # 假设背景+前景杂噪
_, labels, centers = cv2.kmeans(pixels_for_kmeans, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
counts = np.bincount(labels.flatten())
dominant_idx = np.argmax(counts)
fill_rgb = centers[dominant_idx].astype(int)
except Exception:
pass # 保持中位数结果
# --- 2. 提取描边色 (Stroke Color) ---
border_w = max(2, stroke_width)
top = roi_rgb[:border_w, :]
bottom = roi_rgb[h_box-border_w:, :]
left = roi_rgb[:, :border_w]
right = roi_rgb[:, w_box-border_w:]
border_pixels = np.concatenate([
top.reshape(-1, 3),
bottom.reshape(-1, 3),
left.reshape(-1, 3),
right.reshape(-1, 3)
], axis=0)
if border_pixels.size > 0:
# 计算亮度 (Luminance): L = 0.299*R + 0.587*G + 0.114*B
luminance = np.dot(border_pixels, [0.299, 0.587, 0.114])
# 提取最暗的 25% 像素 (假设边框比背景深)
dark_threshold = np.percentile(luminance, 25)
darker_pixels = border_pixels[luminance <= dark_threshold]
if len(darker_pixels) > 0:
stroke_rgb = np.mean(darker_pixels, axis=0).astype(int)
else:
stroke_rgb = np.mean(border_pixels, axis=0).astype(int)
else:
stroke_rgb = np.array([0, 0, 0])
# RGB -> Hex
def rgb2hex(rgb):
return "#{:02x}{:02x}{:02x}".format(*rgb)
# 限制 stroke_width 在合理范围内(1-3),避免过粗的边框
stroke_width = min(3, max(1, stroke_width))
return rgb2hex(fill_rgb), rgb2hex(stroke_rgb), stroke_width
def extract_style_specific(image: np.ndarray, bbox: list, shape_type: str) -> dict:
"""
针对不同基础形状的特定取色和边框算法。
- 对于矩形类形状,使用动态边框宽度检测
- 对于非矩形形状(椭圆、菱形等),使用Mask提取更准确的填充色
"""
fill_hex, stroke_hex, stroke_w = extract_style_colors(image, bbox)
# 针对非矩形形状,使用 Mask 提取更准确的填充色
if shape_type in ["ellipse", "cloud", "circle", "diamond", "triangle", "hexagon"]:
x1, y1, x2, y2 = map(int, bbox)
h_img, w_img = image.shape[:2]
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(w_img, x2), min(h_img, y2)
roi = image[y1:y2, x1:x2]
if roi.size > 0:
h, w = roi.shape[:2]
mask = np.zeros((h, w), dtype=np.uint8)
if shape_type in ["ellipse", "cloud", "circle"]:
cv2.ellipse(mask, (w//2, h//2), (w//2, h//2), 0, 0, 360, 255, -1)
elif shape_type == "diamond":
pts = np.array([[w//2, 0], [w, h//2], [w//2, h], [0, h//2]], dtype=np.int32)
cv2.fillPoly(mask, [pts], 255)
elif shape_type == "triangle":
pts = np.array([[w//2, 0], [w, h], [0, h]], dtype=np.int32)
cv2.fillPoly(mask, [pts], 255)
elif shape_type == "hexagon":
pts = np.array([
[w//4, 0], [w*3//4, 0],
[w, h//2],
[w*3//4, h], [w//4, h],
[0, h//2]
], dtype=np.int32)
cv2.fillPoly(mask, [pts], 255)
# 腐蚀掉边缘区域
kernel_size = max(3, stroke_w * 2 + 1)
kernel = np.ones((kernel_size, kernel_size), np.uint8)
mask = cv2.erode(mask, kernel)
if cv2.countNonZero(mask) > 0:
roi_rgb = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
masked_pixels = roi_rgb[mask > 0]
masked_pixels = masked_pixels.reshape(-1, 3)
if masked_pixels.size > 0:
fill_rgb = np.median(masked_pixels, axis=0).astype(int)
fill_hex = "#{:02x}{:02x}{:02x}".format(*map(int, fill_rgb))
geo_params = extract_geometric_params(image, bbox, shape_type)
return {
"fill_color": fill_hex,
"stroke_color": stroke_hex,
"stroke_width": stroke_w,
"geo_params": geo_params
}
# ======================== Mask精确取色 ========================
def extract_color_with_mask(image: np.ndarray, bbox: list, mask: np.ndarray,
shape_type: str = "unknown") -> dict:
"""
使用SAM3提供的Mask进行精确取色
Args:
image: BGR格式的OpenCV图像
bbox: [x1, y1, x2, y2] 边界框
mask: SAM3提供的二值掩码 (full size or cropped)
shape_type: 形状类型
Returns:
{
'fill_color': '#xxxxxx',
'stroke_color': '#xxxxxx',
'stroke_width': int,
'geo_params': dict,
'has_gradient': bool,
'gradient_info': dict or None
}
"""
x1, y1, x2, y2 = map(int, bbox)
h_img, w_img = image.shape[:2]
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(w_img, x2), min(h_img, y2)
roi = image[y1:y2, x1:x2]
roi_rgb = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
h_roi, w_roi = roi.shape[:2]
if h_roi == 0 or w_roi == 0:
return {
'fill_color': '#ffffff',
'stroke_color': '#000000',
'stroke_width': 1,
'geo_params': {},
'has_gradient': False,
'gradient_info': None
}
# 处理Mask:确保和ROI尺寸一致
if mask is not None and mask.size > 0:
# 如果mask是全图尺寸,裁剪到ROI
if mask.shape[0] == h_img and mask.shape[1] == w_img:
mask_crop = mask[y1:y2, x1:x2]
elif mask.shape[0] == h_roi and mask.shape[1] == w_roi:
mask_crop = mask
else:
# 尺寸不匹配,resize
mask_crop = cv2.resize(mask.astype(np.uint8), (w_roi, h_roi))
# 二值化
if mask_crop.max() > 1:
mask_crop = (mask_crop > 127).astype(np.uint8)
else:
mask_crop = mask_crop.astype(np.uint8)
else:
# 没有mask,创建全1掩码
mask_crop = np.ones((h_roi, w_roi), dtype=np.uint8)
# =========== 1. 使用Mask精确提取填充色 ===========
# 腐蚀Mask去除边框区域
kernel_erode = np.ones((5, 5), np.uint8)
inner_mask = cv2.erode(mask_crop, kernel_erode, iterations=2)
# 提取内部像素
if cv2.countNonZero(inner_mask) > 10:
fill_pixels = roi_rgb[inner_mask > 0]
else:
fill_pixels = roi_rgb[mask_crop > 0] if cv2.countNonZero(mask_crop) > 0 else roi_rgb.reshape(-1, 3)
if len(fill_pixels) > 0:
fill_pixels = fill_pixels.reshape(-1, 3)
# K-Means找主色(比中位数更准确)
if len(fill_pixels) > 50:
try:
pixels_f32 = fill_pixels.astype(np.float32)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
k = min(3, len(fill_pixels) // 20)
k = max(2, k)
_, labels, centers = cv2.kmeans(pixels_f32, k, None, criteria, 5, cv2.KMEANS_RANDOM_CENTERS)
# 选择占比最大的颜色
counts = np.bincount(labels.flatten())
dominant_idx = np.argmax(counts)
fill_rgb = centers[dominant_idx].astype(int)
except Exception:
fill_rgb = np.median(fill_pixels, axis=0).astype(int)
else:
fill_rgb = np.median(fill_pixels, axis=0).astype(int)
else:
fill_rgb = np.array([255, 255, 255])
# =========== 2. 使用Mask边缘提取描边色 ===========
# 获取Mask边缘
edge_mask = mask_crop - inner_mask
edge_mask = np.maximum(edge_mask, 0).astype(np.uint8)
# 如果边缘太薄,膨胀一下
if cv2.countNonZero(edge_mask) < 50:
kernel_edge = np.ones((3, 3), np.uint8)
dilated_mask = cv2.dilate(mask_crop, kernel_edge, iterations=1)
edge_mask = dilated_mask - cv2.erode(mask_crop, kernel_edge, iterations=1)
edge_mask = np.maximum(edge_mask, 0).astype(np.uint8)
if cv2.countNonZero(edge_mask) > 5:
stroke_pixels = roi_rgb[edge_mask > 0].reshape(-1, 3)
# 取最暗的像素作为描边色
if len(stroke_pixels) > 0:
luminance = np.dot(stroke_pixels, [0.299, 0.587, 0.114])
dark_threshold = np.percentile(luminance, 30)
dark_pixels = stroke_pixels[luminance <= dark_threshold]
if len(dark_pixels) > 0:
stroke_rgb = np.mean(dark_pixels, axis=0).astype(int)
else:
stroke_rgb = np.mean(stroke_pixels, axis=0).astype(int)
else:
stroke_rgb = np.array([0, 0, 0])
else:
stroke_rgb = np.array([0, 0, 0])
# =========== 3. 估算描边宽度 ===========
# 基于Mask边缘厚度,限制在1-3范围内
if cv2.countNonZero(edge_mask) > 0:
# 计算边缘区域的平均厚度
dist_transform = cv2.distanceTransform(mask_crop, cv2.DIST_L2, 5)
max_dist = dist_transform.max()
stroke_width = max(1, min(3, int(max_dist * 0.15))) # 限制最大为3
else:
stroke_width = 1
# =========== 4. 检测渐变 ===========
has_gradient = False
gradient_info = None
if len(fill_pixels) > 100:
# 将填充区域分为上下/左右两半,比较颜色差异
coords = np.argwhere(inner_mask > 0 if cv2.countNonZero(inner_mask) > 10 else mask_crop > 0)
if len(coords) > 20:
mid_y = (coords[:, 0].min() + coords[:, 0].max()) // 2
mid_x = (coords[:, 1].min() + coords[:, 1].max()) // 2
# 上下分区
top_coords = coords[coords[:, 0] < mid_y]
bottom_coords = coords[coords[:, 0] >= mid_y]
if len(top_coords) > 10 and len(bottom_coords) > 10:
top_colors = roi_rgb[top_coords[:, 0], top_coords[:, 1]]
bottom_colors = roi_rgb[bottom_coords[:, 0], bottom_coords[:, 1]]
top_mean = np.mean(top_colors, axis=0)
bottom_mean = np.mean(bottom_colors, axis=0)
v_diff = np.linalg.norm(top_mean - bottom_mean)
if v_diff > 35:
has_gradient = True
gradient_info = {
'direction': 'vertical',
'start_color': "#{:02x}{:02x}{:02x}".format(*top_mean.astype(int).clip(0, 255)),
'end_color': "#{:02x}{:02x}{:02x}".format(*bottom_mean.astype(int).clip(0, 255))
}
# 左右分区(如果垂直没有渐变)
if not has_gradient:
left_coords = coords[coords[:, 1] < mid_x]
right_coords = coords[coords[:, 1] >= mid_x]
if len(left_coords) > 10 and len(right_coords) > 10:
left_colors = roi_rgb[left_coords[:, 0], left_coords[:, 1]]
right_colors = roi_rgb[right_coords[:, 0], right_coords[:, 1]]
left_mean = np.mean(left_colors, axis=0)
right_mean = np.mean(right_colors, axis=0)
h_diff = np.linalg.norm(left_mean - right_mean)
if h_diff > 35:
has_gradient = True
gradient_info = {
'direction': 'horizontal',
'start_color': "#{:02x}{:02x}{:02x}".format(*left_mean.astype(int).clip(0, 255)),
'end_color': "#{:02x}{:02x}{:02x}".format(*right_mean.astype(int).clip(0, 255))
}
# =========== 5. 提取几何参数 ===========
geo_params = extract_geometric_params(image, bbox, shape_type)
# 格式化输出
fill_color = "#{:02x}{:02x}{:02x}".format(*fill_rgb.clip(0, 255))
stroke_color = "#{:02x}{:02x}{:02x}".format(*stroke_rgb.clip(0, 255))
return {
'fill_color': fill_color,
'stroke_color': stroke_color,
'stroke_width': stroke_width,
'geo_params': geo_params,
'has_gradient': has_gradient,
'gradient_info': gradient_info
}
# ======================== 样式统一 ========================
def unify_element_styles(elements: list) -> list:
"""
统一相似大小和类型的基本图形的边框厚度。
注意:参考 sam3_extractor.py 的简化逻辑,默认边框宽度为1,
这里主要用于确保同类元素风格一致。
"""
if not elements:
return elements
groups = {}
for i, elem in enumerate(elements):
shape_type = elem.get("_type", "rectangle")
bbox = elem["bbox"]
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
diag = math.sqrt(w**2 + h**2)
size_key = int(round(diag / 20))
key = (shape_type, size_key)
if key not in groups:
groups[key] = []
groups[key].append(i)
for key, indices in groups.items():
if len(indices) < 2:
continue
# 获取边框宽度,如果不存在则默认为1
widths = []
for i in indices:
style = elements[i].get("_style", {})
widths.append(style.get("stroke_width", 1))
if not widths:
continue
median_width = int(np.median(widths))
for i in indices:
if "_style" not in elements[i]:
elements[i]["_style"] = {}
elements[i]["_style"]["stroke_width"] = median_width
return elements
# ======================== CV矩形检测优化辅助函数 ========================
def _merge_nearby_lines(lines, threshold=10):
"""
合并相近的平行线段,减少冗余
Args:
lines: 线段列表,格式为 [(y, x1, x2), ...] 或 [(x, y1, y2), ...]
threshold: 合并阈值,位置差小于此值的线段会被合并
Returns:
合并后的线段列表
"""
if not lines:
return []
merged = []
used = set()
for i, line in enumerate(lines):
if i in used:
continue
pos, start, end = line # y/x, x1/y1, x2/y2
# 找到所有相近的线段
group_pos = [pos]
group_start = [start]
group_end = [end]
for j, other in enumerate(lines[i+1:], i+1):
if j in used:
continue
o_pos, o_start, o_end = other
if abs(o_pos - pos) < threshold:
group_pos.append(o_pos)
group_start.append(o_start)
group_end.append(o_end)
used.add(j)
# 合并为一条线
merged.append((
int(np.mean(group_pos)),
min(group_start),
max(group_end)
))
used.add(i)
return merged
# ======================== CV结果验证 ========================
def _validate_cv_rectangle(cv2_image: np.ndarray, bbox: list, min_std: float = 8) -> bool:
"""
验证CV检测到的矩形是否有效
检查内容:
1. 内部颜色是否有足够变化(排除纯色背景误检)
2. 边框与内部是否有明显区别
:param cv2_image: BGR图像
:param bbox: [x1, y1, x2, y2]
:param min_std: 最小颜色标准差
:return: True=有效, False=可能是误检
"""
x1, y1, x2, y2 = map(int, bbox)
h, w = cv2_image.shape[:2]
# 边界检查
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(w, x2), min(h, y2)
if x2 - x1 < 20 or y2 - y1 < 20:
return False
roi = cv2_image[y1:y2, x1:x2]
gray_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
# 检查1:内部是否有足够的颜色变化
roi_h, roi_w = gray_roi.shape
margin = max(3, min(roi_w, roi_h) // 10)
if roi_h > 2 * margin and roi_w > 2 * margin:
inner = gray_roi[margin:-margin, margin:-margin]
inner_std = np.std(inner)
# 如果内部颜色太均匀,可能是误检的背景区域
if inner_std < min_std:
return False
# 检查2:边框与内部是否有对比度
border_size = max(2, min(roi_w, roi_h) // 20)
if roi_h > 2 * border_size and roi_w > 2 * border_size:
border_top = gray_roi[:border_size, :].mean()
border_bottom = gray_roi[-border_size:, :].mean()
border_left = gray_roi[:, :border_size].mean()
border_right = gray_roi[:, -border_size:].mean()
border_mean = np.mean([border_top, border_bottom, border_left, border_right])
inner_region = gray_roi[border_size:-border_size, border_size:-border_size]
inner_mean = inner_region.mean()
contrast = abs(border_mean - inner_mean)
# 边框和内部需要有一定对比度
if contrast < 5:
return False
return True
# ======================== CV矩形检测 ========================
def detect_rectangles_robust(cv2_image: np.ndarray, existing_elements: dict, config: dict = None) -> dict:
"""
精准矩形检测(补充SAM3遗漏的矩形)
采用保守策略:
- 默认只启用可靠的检测方法(contour, nested_contour)
- 提高检测门槛减少误检
- 对检测结果进行内容验证
:param cv2_image: BGR格式的OpenCV图像
:param existing_elements: SAM3已识别的元素字典
:param config: 配置参数字典
:return: {"rectangles": [...], "containers": [...]}
"""
default_config = {
# 面积限制(提高门槛减少误检)
"min_area": 5000, # 提高最小面积(原3000)
"min_area_ratio": 0.005, # 最小面积占比
"max_area_ratio": 0.5,
# 去重阈值(更积极去重)
"iou_threshold": 0.2, # 降低IoU阈值(原0.3)
"nms_threshold": 0.25, # 降低NMS阈值(原0.3)
# 形状验证(提高要求)
"min_rectangularity": 0.7, # 提高矩形度(原0.6)
"border_contrast": 15, # 提高边框对比度(原10)
# 容器检测
"container_threshold": 0.8,
"min_contained": 3,
# 启用的检测方法(保守模式:只启用可靠的方法)
"enabled_methods": ["contour", "nested_contour"],
# 完整模式可用: ["contour", "region", "low_contrast", "hough_lines", "nested_contour"]
# 内容验证(CV结果需要通过验证)
"validate_content": True,
"min_content_std": 8, # 内部颜色标准差阈值
}
cfg = {**default_config, **(config or {})}
enabled_methods = set(cfg.get("enabled_methods", ["contour", "nested_contour"]))
h, w = cv2_image.shape[:2]
total_area = h * w
max_area = total_area * cfg["max_area_ratio"]
min_area = max(cfg["min_area"], int(total_area * cfg.get("min_area_ratio", 0)))
# 收集SAM3已检测的bbox
sam3_bboxes = []
for elem_type, items in existing_elements.items():
for item in items:
sam3_bboxes.append({"bbox": item["bbox"], "type": elem_type})
all_candidates = []
gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY)
# 方法1:边缘轮廓检测(最可靠的方法)
if "contour" in enabled_methods:
edges = cv2.Canny(gray, 30, 100)
edges = cv2.dilate(edges, np.ones((2, 2), np.uint8), iterations=1)
contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
peri = cv2.arcLength(cnt, True)
if peri < 100:
continue
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
if not (4 <= len(approx) <= 8):
continue
x, y, rw, rh = cv2.boundingRect(approx)
bbox = [x, y, x+rw, y+rh]
area = rw * rh
if area < min_area or area > max_area:
continue
aspect = max(rw, rh) / max(1, min(rw, rh))
if aspect > 4:
continue
cnt_area = cv2.contourArea(approx)
rectangularity = cnt_area / area if area > 0 else 0
if rectangularity < cfg["min_rectangularity"]:
continue
# 验证边框线
border_w = max(3, min(8, rw // 15, rh // 15))
if rw > 2 * border_w and rh > 2 * border_w:
roi = gray[y:y+rh, x:x+rw]
border_top = roi[:border_w, :].flatten()
border_bottom = roi[-border_w:, :].flatten()
border_left = roi[:, :border_w].flatten()
border_right = roi[:, -border_w:].flatten()
border_pixels = np.concatenate([border_top, border_bottom, border_left, border_right])
inner = roi[border_w:-border_w, border_w:-border_w].flatten()
if len(inner) > 0 and len(border_pixels) > 0:
border_mean = np.mean(border_pixels)
inner_mean = np.mean(inner)
contrast = abs(border_mean - inner_mean)
if contrast < cfg["border_contrast"]:
continue
is_rounded = rectangularity < 0.98
all_candidates.append({
"bbox": bbox,
"area": area,
"method": "contour",
"score": rectangularity,
"rectangularity": rectangularity,
"is_rounded": is_rounded
})
# 方法2:区域颜色检测(容易误检,默认禁用)
if "region" in enabled_methods:
hsv = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2HSV)
lower_gray = np.array([0, 0, 180])
upper_gray = np.array([180, 50, 252])
mask_region = cv2.inRange(hsv, lower_gray, upper_gray)
kernel_open = np.ones((3, 3), np.uint8)
kernel_close_region = np.ones((7, 7), np.uint8)
mask_region = cv2.morphologyEx(mask_region, cv2.MORPH_OPEN, kernel_open)
mask_region = cv2.morphologyEx(mask_region, cv2.MORPH_CLOSE, kernel_close_region)
contours_region, _ = cv2.findContours(mask_region, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours_region:
peri = cv2.arcLength(cnt, True)
if peri < 100:
continue
approx = cv2.approxPolyDP(cnt, 0.02 * peri, True)
if not (4 <= len(approx) <= 12):
continue
x, y, rw, rh = cv2.boundingRect(approx)
bbox = [x, y, x+rw, y+rh]
area = rw * rh
if area < min_area or area > max_area:
continue
if max(rw, rh) / max(1, min(rw, rh)) > 5:
continue
cnt_area = cv2.contourArea(approx)
if area > 0 and cnt_area / area < 0.6:
continue
rect_ratio = cnt_area / area if area > 0 else 0
is_rounded_region = False
if 0.85 <= rect_ratio < 0.96:
is_rounded_region = True
elif len(approx) > 4 and rect_ratio < 0.96:
is_rounded_region = True
all_candidates.append({
"bbox": bbox,
"area": area,
"method": "region",
"score": rect_ratio,
"rectangularity": rect_ratio,
"is_rounded": is_rounded_region
})
# 方法3:低对比度框检测(容易误检,默认禁用,通过 enabled_methods 过滤)
edges_low = cv2.Canny(gray, 10, 50)
edges_low = cv2.dilate(edges_low, np.ones((3, 3), np.uint8), iterations=2)
kernel_close = np.ones((5, 5), np.uint8)