-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
873 lines (716 loc) · 30.6 KB
/
Copy pathmain.py
File metadata and controls
873 lines (716 loc) · 30.6 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
import cv2
import numpy as np
from pathlib import Path
def order_points(pts):
"""
按照左上、右上、右下、左下的顺序排序四个点
参数:
pts: 四个点的坐标数组
返回:
按照正确顺序排列的四个点
"""
# 计算每个点到原点的距离
rect = np.zeros((4, 2), dtype="float32")
# 计算坐标之和,最小的是左上角,最大的是右下角
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)] # 左上
rect[2] = pts[np.argmax(s)] # 右下
# 计算坐标差,最小的是右上角,最大的是左下角
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)] # 右上
rect[3] = pts[np.argmax(diff)] # 左下
return rect
def smooth_projection(projection, window_size=5):
"""
对投影曲线进行平滑处理,减少噪声影响
参数:
projection: 投影数组
window_size: 平滑窗口大小
返回:
平滑后的投影数组
"""
if window_size % 2 == 0:
window_size += 1
smoothed = np.copy(projection)
half_window = window_size // 2
for i in range(half_window, len(projection) - half_window):
smoothed[i] = np.mean(projection[i - half_window:i + half_window + 1])
return smoothed
def ratio_to_pixel_coordinates(ratio_coords, image_width, image_height):
"""
将比例坐标转换为像素坐标
参数:
ratio_coords: 比例坐标列表
image_width: 图像宽度
image_height: 图像高度
返回:
像素坐标列表
"""
pixel_coords = []
# 中文到英文的映射
english_to_chinese = {
'Departure': '起始站',
'Arrival': '到达站',
'TrainNo': '车次',
'Class': '等级',
'Time': '时间',
'Price': '价格',
'Other': '其他'
}
for elem in ratio_coords:
pixel_elem = {
'type': english_to_chinese.get(elem['type'], elem['type']),
'x1': int(elem['x1'] * image_width),
'y1': int(elem['y1'] * image_height),
'x2': int(elem['x2'] * image_width),
'y2': int(elem['y2'] * image_height),
'width': int(elem['width_ratio'] * image_width),
'height': int(elem['height_ratio'] * image_height)
}
pixel_coords.append(pixel_elem)
return pixel_coords
def read_element_coordinates_from_json(output_path):
"""
从JSON文件中读取要素比例坐标
参数:
output_path: 输出目录
返回:
要素比例坐标列表,如果文件不存在则返回None
"""
import json
from pathlib import Path
# 查找json文件
json_file = Path(output_path) / 'element_ratio_coordinates.json'
if not json_file.exists():
# 尝试在主输出目录查找
main_json_file = Path(output_path).parent / 'element_ratio_coordinates.json'
if not main_json_file.exists():
return None
json_file = main_json_file
try:
with open(json_file, 'r', encoding='utf-8') as f:
ratio_coords = json.load(f)
print(f"从 {json_file} 读取到 {len(ratio_coords)} 个要素坐标")
return ratio_coords
except Exception as e:
print(f"读取JSON文件失败: {e}")
return None
def calculate_text_density(region):
"""
计算区域的文本密度
参数:
region: 灰度图像区域
返回:
文本密度值(0-1之间)
"""
if region.size == 0:
return 0
# 转换为灰度图
if len(region.shape) == 3:
gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)
else:
gray = region
# 二值化
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
# 计算白色像素比例(文本密度)
text_density = cv2.countNonZero(binary) / gray.size
return text_density
def evaluate_region_quality(region, position, image_size):
"""
评估区域质量分数
参数:
region: 图像区域
position: 区域位置 (x1, y1, x2, y2)
image_size: 图像尺寸 (width, height)
返回:
质量分数(0-1之间)
"""
x1, y1, x2, y2 = position
width, height = image_size
# 计算基本特征
region_width = x2 - x1
region_height = y2 - y1
aspect_ratio = region_width / region_height if region_height > 0 else 0
# 文本密度得分(0.4权重)
text_density = calculate_text_density(region)
density_score = text_density
# 尺寸得分(0.3权重)
# 合理的宽度范围:10% - 80% 图像宽度
width_score = max(0, min(1, (region_width - 0.1 * width) / (0.7 * width)))
# 合理的高度范围:5% - 30% 图像高度
height_score = max(0, min(1, (region_height - 0.05 * height) / (0.25 * height)))
size_score = (width_score + height_score) / 2
# 位置得分(0.3权重)
# 火车票要素通常分布在图像上半部分和中部
position_score = 1 - (y1 + y2) / (2 * height) # 越靠上得分越高
# 总得分
total_score = 0.4 * density_score + 0.3 * size_score + 0.3 * position_score
return total_score
def segment_ticket_elements(ticket_img, output_path, processing_steps_dir=None):
"""
分割火车票要素
参数:
ticket_img: 旋正后的火车票图像
output_path: 输出目录
processing_steps_dir: 处理步骤保存目录
返回:
包含各要素信息的字典
"""
# 转换为灰度图
gray = cv2.cvtColor(ticket_img, cv2.COLOR_BGR2GRAY)
# 使用高斯模糊减少噪声
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 自适应二值化(增强对比度,更好地处理不同光照区域)
binary = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
# 反转二值图(黑底白字更容易处理)
binary_inv = cv2.bitwise_not(binary)
# 保存中间处理步骤图像
if processing_steps_dir:
cv2.imwrite(f'{processing_steps_dir}/01_gray.jpg', gray)
cv2.imwrite(f'{processing_steps_dir}/02_blurred.jpg', blurred)
cv2.imwrite(f'{processing_steps_dir}/03_binary.jpg', binary)
cv2.imwrite(f'{processing_steps_dir}/04_binary_inv.jpg', binary_inv)
height, width = ticket_img.shape[:2]
# 尝试从JSON文件读取要素坐标
ratio_coords = read_element_coordinates_from_json(output_path)
# 如果JSON文件不存在或读取失败,使用内置的要素比例坐标
if ratio_coords is None:
# 内置的要素比例坐标
ratio_coords = [
{
"type": "Departure",
"x1": 0.11002661934338953,
"y1": 0.11159420289855072,
"x2": 0.37888198757763975,
"y2": 0.2811594202898551,
"width_ratio": 0.2688553682342502,
"height_ratio": 0.16956521739130434
},
{
"type": "Arrival",
"x1": 0.64773735581189,
"y1": 0.1072463768115942,
"x2": 0.9174800354924578,
"y2": 0.2811594202898551,
"width_ratio": 0.26974267968056787,
"height_ratio": 0.17391304347826086
},
{
"type": "TrainNo",
"x1": 0.4072759538598048,
"y1": 0.11594202898550725,
"x2": 0.6175687666370896,
"y2": 0.22608695652173913,
"width_ratio": 0.21029281277728482,
"height_ratio": 0.11014492753623188
},
{
"type": "Class",
"x1": 0.6912156166814551,
"y1": 0.36376811594202896,
"x2": 0.8376220053238687,
"y2": 0.4434782608695652,
"width_ratio": 0.14640638864241348,
"height_ratio": 0.07971014492753623
},
{
"type": "Time",
"x1": 0.07630878438331855,
"y1": 0.2797101449275362,
"x2": 0.5634427684117125,
"y2": 0.36376811594202896,
"width_ratio": 0.487133984028394,
"height_ratio": 0.08405797101449275
},
{
"type": "Price",
"x1": 0.0771960958296362,
"y1": 0.36666666666666664,
"x2": 0.26353149955634425,
"y2": 0.4463768115942029,
"width_ratio": 0.18633540372670807,
"height_ratio": 0.07971014492753623
}
]
# 计算水平投影(垂直方向的投影)
horizontal_projection = np.sum(binary_inv, axis=1)
# 计算垂直投影(水平方向的投影)
vertical_projection = np.sum(binary_inv, axis=0)
# 结合要素坐标信息增强投影曲线
if ratio_coords:
# 将比例坐标转换为像素坐标
pixel_coords_temp = ratio_to_pixel_coordinates(ratio_coords, width, height)
# 增强水平投影:根据要素的垂直位置
for elem in pixel_coords_temp:
y_start = max(0, int(elem['y1']))
y_end = min(height, int(elem['y2']))
# 在要素区域内增强水平投影值
for y in range(y_start, y_end):
if y < len(horizontal_projection):
horizontal_projection[y] *= 1.5 # 增强要素区域的投影值
# 增强垂直投影:根据要素的水平位置
for elem in pixel_coords_temp:
x_start = max(0, int(elem['x1']))
x_end = min(width, int(elem['x2']))
# 在要素区域内增强垂直投影值
for x in range(x_start, x_end):
if x < len(vertical_projection):
vertical_projection[x] *= 1.5 # 增强要素区域的投影值
# 平滑投影曲线,减少噪声影响
# 调整窗口大小,水平方向使用较大窗口,垂直方向使用较小窗口
horizontal_projection = smooth_projection(horizontal_projection, window_size=9)
vertical_projection = smooth_projection(vertical_projection, window_size=5)
# 根据投影寻找分割线(投影值为0或很小的地方)
# 调整阈值,使用相对阈值而非绝对阈值
h_threshold = np.max(horizontal_projection) * 0.25 # 调整阈值,提高敏感度
v_threshold = np.max(vertical_projection) * 0.15 # 调整阈值,提高敏感度
# 找到水平分割线(文本行的分界)
h_lines = []
in_line = False
start = 0
for i, val in enumerate(horizontal_projection):
if val > h_threshold and not in_line:
in_line = True
start = i
elif val <= h_threshold and in_line:
in_line = False
h_lines.append((start, i))
if in_line:
h_lines.append((start, len(horizontal_projection)))
# 找到垂直分割线(文本列的分界)
v_lines = []
in_line = False
start = 0
for i, val in enumerate(vertical_projection):
if val > v_threshold and not in_line:
in_line = True
start = i
elif val <= v_threshold and in_line:
in_line = False
v_lines.append((start, i))
if in_line:
v_lines.append((start, len(vertical_projection)))
# 结合要素坐标优化分割线
if ratio_coords:
# 将比例坐标转换为像素坐标
pixel_coords_temp = ratio_to_pixel_coordinates(ratio_coords, width, height)
# 优化水平分割线:确保分割线与要素边界对齐
optimized_h_lines = []
for line in h_lines:
start, end = line
# 检查是否需要调整以匹配要素边界
adjusted = False
for elem in pixel_coords_temp:
elem_top = int(elem['y1'])
elem_bottom = int(elem['y2'])
# 如果分割线接近要素边界,调整到要素边界
if abs(start - elem_top) < 10:
start = elem_top
adjusted = True
if abs(end - elem_bottom) < 10:
end = elem_bottom
adjusted = True
if adjusted:
optimized_h_lines.append((start, end))
else:
optimized_h_lines.append(line)
h_lines = optimized_h_lines
# 优化垂直分割线:确保分割线与要素边界对齐
optimized_v_lines = []
for line in v_lines:
start, end = line
# 检查是否需要调整以匹配要素边界
adjusted = False
for elem in pixel_coords_temp:
elem_left = int(elem['x1'])
elem_right = int(elem['x2'])
# 如果分割线接近要素边界,调整到要素边界
if abs(start - elem_left) < 10:
start = elem_left
adjusted = True
if abs(end - elem_right) < 10:
end = elem_right
adjusted = True
if adjusted:
optimized_v_lines.append((start, end))
else:
optimized_v_lines.append(line)
v_lines = optimized_v_lines
# 添加要素边界作为额外的分割线
for elem in pixel_coords_temp:
# 添加要素的水平边界
elem_top = int(elem['y1'])
elem_bottom = int(elem['y2'])
# 检查是否已经存在类似的分割线
top_exists = any(abs(line[0] - elem_top) < 5 or abs(line[1] - elem_top) < 5 for line in h_lines)
bottom_exists = any(abs(line[0] - elem_bottom) < 5 or abs(line[1] - elem_bottom) < 5 for line in h_lines)
if not top_exists:
h_lines.append((elem_top, elem_top + 1))
if not bottom_exists:
h_lines.append((elem_bottom - 1, elem_bottom))
# 添加要素的垂直边界
elem_left = int(elem['x1'])
elem_right = int(elem['x2'])
# 检查是否已经存在类似的分割线
left_exists = any(abs(line[0] - elem_left) < 5 or abs(line[1] - elem_left) < 5 for line in v_lines)
right_exists = any(abs(line[0] - elem_right) < 5 or abs(line[1] - elem_right) < 5 for line in v_lines)
if not left_exists:
v_lines.append((elem_left, elem_left + 1))
if not right_exists:
v_lines.append((elem_right - 1, elem_right))
# 去重并排序分割线
h_lines = sorted(list(set(h_lines)), key=lambda x: x[0])
v_lines = sorted(list(set(v_lines)), key=lambda x: x[0])
# 将比例坐标转换为像素坐标
pixel_coords = ratio_to_pixel_coordinates(ratio_coords, width, height)
# 根据火车票版面结构分析各要素位置
elements = analyze_ticket_layout(ticket_img, h_lines, v_lines, output_path, pixel_coords, processing_steps_dir)
return elements
def analyze_ticket_layout(ticket_img, h_lines, v_lines, output_path, pixel_coords=None, processing_steps_dir=None):
"""
根据火车票的标准版面结构分析各要素
返回:
各要素的位置和图像
"""
height, width = ticket_img.shape[:2]
elements = {}
# 创建标记图
marked_img = ticket_img.copy()
# 定义颜色
colors = {
'起始站': (255, 0, 0), # 蓝色
'到达站': (0, 255, 0), # 绿色
'车次': (0, 0, 255), # 红色
'等级': (255, 255, 0), # 青色
'时间': (255, 0, 255), # 紫色
'价格': (0, 255, 255), # 黄色
}
# 分析区域分布,按高度顺序
# 如果有预定义的像素坐标,直接使用这些坐标进行要素分割
if pixel_coords:
element_idx = 0
for elem in pixel_coords:
# 确保坐标在有效范围内
x_start = max(0, elem['x1'])
y_start = max(0, elem['y1'])
x_end = min(width, elem['x2'])
y_end = min(height, elem['y2'])
elements[elem['type']] = extract_element(ticket_img, x_start, y_start,
x_end, y_end, elem['type'], element_idx, output_path)
cv2.rectangle(marked_img, (x_start, y_start),
(x_end, y_end), colors.get(elem['type'], (100, 100, 100)), 2)
element_idx += 1
# 如果没有预定义坐标,使用传统的投影分析方法
else:
# 首先过滤掉太小的区域
min_region_height = 10
valid_h_lines = [line for line in h_lines if line[1] - line[0] > min_region_height]
if len(valid_h_lines) < 5:
print(f"警告: 有效水平区域不足(仅检测到 {len(valid_h_lines)} 个)")
# 计算垂直区域的中心和大小,并过滤掉太小的垂直区域
min_vertical_width = 20
vertical_regions = []
for i, (x_start, x_end) in enumerate(v_lines):
region_width = x_end - x_start
if region_width < min_vertical_width:
continue # 跳过太小的垂直区域
region_center = (x_start + x_end) // 2
vertical_regions.append({
'index': i,
'x_start': x_start,
'x_end': x_end,
'width': region_width,
'center': region_center
})
# 如果过滤后垂直区域不足,使用自定义的垂直划分
if len(vertical_regions) < 3:
# 根据火车票的典型结构,手动划分三个垂直区域
third_width = width // 3
vertical_regions = [
{'index': 0, 'x_start': 0, 'x_end': third_width, 'width': third_width, 'center': third_width // 2},
{'index': 1, 'x_start': third_width, 'x_end': 2 * third_width, 'width': third_width, 'center': third_width + third_width // 2},
{'index': 2, 'x_start': 2 * third_width, 'x_end': width, 'width': width - 2 * third_width, 'center': 2 * third_width + (width - 2 * third_width) // 2}
]
# 根据火车票实际结构进行要素定位
element_idx = 0
# 1. 顶部区域(起始站、车次、到达站)- 选择高度适中的顶部区域
# 寻找合适的顶部区域(高度在20-50之间,位于图像上半部分)
top_region = None
for line in valid_h_lines:
y_start, y_end = line
region_height = y_end - y_start
if 20 <= region_height <= 50 and y_start < height // 2:
top_region = line
break
# 如果没有找到合适的顶部区域,使用第一个有效区域
if not top_region and valid_h_lines:
top_region = valid_h_lines[0]
if top_region:
top_y_start, top_y_end = top_region
# 根据垂直区域划分顶部区域
if len(vertical_regions) >= 3:
# 左侧区域 - 起始站
left_v_region = vertical_regions[0]
elements['起始站'] = extract_element(ticket_img, left_v_region['x_start'], top_y_start,
left_v_region['x_end'], top_y_end, '起始站', element_idx, output_path)
cv2.rectangle(marked_img, (left_v_region['x_start'], top_y_start),
(left_v_region['x_end'], top_y_end), colors['起始站'], 2)
element_idx += 1
# 中间区域 - 车次
middle_v_region = vertical_regions[1]
elements['车次'] = extract_element(ticket_img, middle_v_region['x_start'], top_y_start,
middle_v_region['x_end'], top_y_end, '车次', element_idx, output_path)
cv2.rectangle(marked_img, (middle_v_region['x_start'], top_y_start),
(middle_v_region['x_end'], top_y_end), colors['车次'], 2)
element_idx += 1
# 右侧区域 - 到达站
right_v_region = vertical_regions[-1]
elements['到达站'] = extract_element(ticket_img, right_v_region['x_start'], top_y_start,
right_v_region['x_end'], top_y_end, '到达站', element_idx, output_path)
cv2.rectangle(marked_img, (right_v_region['x_start'], top_y_start),
(right_v_region['x_end'], top_y_end), colors['到达站'], 2)
element_idx += 1
# 2. 中间区域(等级、时间等)- 选择顶部区域下方的几个区域
if len(valid_h_lines) >= 3:
# 找到顶部区域在valid_h_lines中的索引
top_idx = 0
if top_region:
for i, line in enumerate(valid_h_lines):
if line == top_region:
top_idx = i
break
# 等级区域 - 顶部区域下方第一个区域
if top_idx + 1 < len(valid_h_lines):
level_region = valid_h_lines[top_idx + 1]
level_y_start, level_y_end = level_region
elements['等级'] = extract_element(ticket_img, 0, level_y_start,
width, level_y_end, '等级', element_idx, output_path)
cv2.rectangle(marked_img, (0, level_y_start), (width, level_y_end), colors['等级'], 2)
element_idx += 1
# 时间区域 - 顶部区域下方第二个区域
if top_idx + 2 < len(valid_h_lines):
time_region = valid_h_lines[top_idx + 2]
time_y_start, time_y_end = time_region
elements['时间'] = extract_element(ticket_img, 0, time_y_start,
width, time_y_end, '时间', element_idx, output_path)
cv2.rectangle(marked_img, (0, time_y_start), (width, time_y_end), colors['时间'], 2)
element_idx += 1
# 3. 底部区域(价格等)- 选择图像下半部分的较小区域
# 寻找合适的价格区域(高度在10-30之间,位于图像下半部分)
price_region = None
for line in reversed(valid_h_lines):
y_start, y_end = line
region_height = y_end - y_start
if 10 <= region_height <= 30 and y_start > height // 2:
price_region = line
break
# 如果没有找到合适的价格区域,使用倒数第二个有效区域
if not price_region and len(valid_h_lines) >= 2:
price_region = valid_h_lines[-2]
elif not price_region and valid_h_lines:
price_region = valid_h_lines[-1]
if price_region:
price_y_start, price_y_end = price_region
elements['价格'] = extract_element(ticket_img, 0, price_y_start,
width, price_y_end, '价格', element_idx, output_path)
cv2.rectangle(marked_img, (0, price_y_start), (width, price_y_end), colors['价格'], 2)
element_idx += 1
# 保存标记图像
if processing_steps_dir:
cv2.imwrite(f'{processing_steps_dir}/05_segmented_regions.jpg', marked_img)
else:
cv2.imwrite(f'{output_path}/segmented_regions.jpg', marked_img)
return elements
def extract_element(ticket_img, x_start, y_start, x_end, y_end, element_name, element_idx, output_path):
"""
提取火车票的某个要素
参数:
ticket_img: 火车票图像
x_start, y_start, x_end, y_end: 要素的边界框
element_name: 要素名称(中文)
element_idx: 要素索引号(用于文件名)
output_path: 输出路径
返回:
提取的要素图像路径
"""
# 中文到英文的映射
chinese_to_english = {
'起始站': 'departure_station',
'到达站': 'arrival_station',
'车次': 'train_number',
'等级': 'train_class',
'座号': 'seat_number',
'时间': 'time_info',
'价格': 'price'
}
# 确保坐标在有效范围内
height, width = ticket_img.shape[:2]
x_start = max(0, x_start)
y_start = max(0, y_start)
x_end = min(width, x_end)
y_end = min(height, y_end)
# 提取感兴趣区域
roi = ticket_img[y_start:y_end, x_start:x_end]
# 获取英文名称
english_name = chinese_to_english.get(element_name, element_name)
# 保存提取的要素(使用英文文件名)
output_file = f'{output_path}/20_element_{element_idx:02d}_{english_name}.jpg'
cv2.imwrite(output_file, roi)
return {
'name': element_name,
'english_name': english_name,
'bbox': (x_start, y_start, x_end, y_end),
'file': output_file,
'shape': roi.shape
}
def read_hsv_config_from_file():
"""
从文件中读取HSV范围配置
返回:
hsv_config: 包含lower_blue1, upper_blue1, lower_blue2, upper_blue2的字典
"""
import json
from pathlib import Path
# 查找HSV配置文件
config_file = Path('output') / 'hsv_config.json'
if not config_file.exists():
return None
try:
with open(config_file, 'r', encoding='utf-8') as f:
hsv_config = json.load(f)
return hsv_config
except:
return None
def detect_and_extract_ticket(image_path, output_path='output'):
"""
使用传统图像处理方法检测浅蓝色火车票,分割裁切并旋正
参数:
image_path: 输入图像路径
output_path: 输出目录
"""
# 创建输出目录
Path(output_path).mkdir(exist_ok=True)
# 创建处理步骤子文件夹
processing_steps_dir = Path(output_path) / 'processing_steps'
processing_steps_dir.mkdir(exist_ok=True)
# 读取图像
img = cv2.imread(image_path)
if img is None:
return
# 保存原始图像
cv2.imwrite(f'{processing_steps_dir}/00_original.jpg', img)
# 转换为HSV色彩空间(更容易检测颜色)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imwrite(f'{processing_steps_dir}/01_hsv.jpg', hsv)
# 从文件读取HSV范围配置
hsv_config = read_hsv_config_from_file()
# 使用HSV配置或默认值
if hsv_config is not None:
# 使用配置文件中的HSV范围
lower_blue1 = np.array(hsv_config['lower_blue1'])
upper_blue1 = np.array(hsv_config['upper_blue1'])
lower_blue2 = np.array(hsv_config['lower_blue2'])
upper_blue2 = np.array(hsv_config['upper_blue2'])
else:
# 定义浅蓝色的HSV范围
lower_blue1 = np.array([81, 16, 146])
upper_blue1 = np.array([108, 126, 205])
lower_blue2 = np.array([100, 40, 80])
upper_blue2 = np.array([130, 200, 220])
# 创建掩码
mask1 = cv2.inRange(hsv, lower_blue1, upper_blue1)
mask2 = cv2.inRange(hsv, lower_blue2, upper_blue2)
mask = cv2.bitwise_or(mask1, mask2)
cv2.imwrite(f'{processing_steps_dir}/02_mask.jpg', mask)
# 形态学操作(闭运算)来填充孔洞
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4))
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=2)
cv2.imwrite(f'{processing_steps_dir}/03_closed.jpg', closed)
# 腐蚀和膨胀来清理噪声
kernel_small = cv2.getStructuringElement(cv2.MORPH_RECT, (30, 30))
cleaned = cv2.morphologyEx(closed, cv2.MORPH_OPEN, kernel_small, iterations=1)
cv2.imwrite(f'{processing_steps_dir}/04_cleaned.jpg', cleaned)
# 直接使用轮廓检测作为主要方法
# 查找轮廓
contours, _ = cv2.findContours(cleaned, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if not contours:
return
# 找到最大的轮廓(最可能是火车票)
largest_contour = max(contours, key=cv2.contourArea)
# 绘制轮廓检测结果
contour_img = img.copy()
cv2.drawContours(contour_img, [largest_contour], 0, (0, 255, 0), 3)
cv2.imwrite(f'{processing_steps_dir}/05_contours.jpg', contour_img)
# 获取最小外接矩形(考虑旋转)
rect = cv2.minAreaRect(largest_contour)
# 获取矩形的四个角点
box_points = cv2.boxPoints(rect)
box_points = np.float32(box_points)
# 绘制矩形框
box = np.int32(box_points)
box_img = img.copy()
cv2.drawContours(box_img, [box], 0, (0, 0, 255), 3)
cv2.imwrite(f'{processing_steps_dir}/06_bounding_box.jpg', box_img)
# 确定长边和短边
rect_width = int(rect[1][0])
rect_height = int(rect[1][1])
if rect_width < rect_height:
rect_width, rect_height = rect_height, rect_width
# 定义目标矩形的四个角点
dst_points = np.float32([
[0, 0],
[rect_width, 0],
[rect_width, rect_height],
[0, rect_height]
])
# 排序源点和目标点
src_points = order_points(box_points)
# 使用透视变换
M = cv2.getPerspectiveTransform(src_points, dst_points)
warped = cv2.warpPerspective(img, M, (rect_width, rect_height))
cv2.imwrite(f'{processing_steps_dir}/07_perspective_transform.jpg', warped)
# 将火车票最终尺寸比例变换为54:85(短边:长边)
target_ratio = 54 / 85 # 短边/长边
# 确定长边和短边
if warped.shape[1] > warped.shape[0]:
long_side = warped.shape[1]
short_side = warped.shape[0]
else:
long_side = warped.shape[0]
short_side = warped.shape[1]
# 按54:85比例计算新的短边长度
new_short_side = int(long_side * target_ratio)
# 确定最终尺寸
if warped.shape[1] > warped.shape[0]:
new_size = (long_side, new_short_side)
else:
new_size = (new_short_side, long_side)
# 调整图像尺寸
cropped = cv2.resize(warped, new_size, interpolation=cv2.INTER_AREA)
cv2.imwrite(f'{processing_steps_dir}/08_resized.jpg', cropped)
# 保存最终结果
cv2.imwrite(f'{output_path}/final_ticket.jpg', cropped)
# 进行要素分割
elements = segment_ticket_elements(cropped, output_path, processing_steps_dir)
return cropped
def main():
"""主函数"""
# 查找当前目录下的图像文件
current_dir = Path(__file__).parent
image_files = list(current_dir.glob('*.jpg')) + list(current_dir.glob('*.jpeg')) + list(current_dir.glob('*.png'))
if not image_files:
return
# 创建主输出目录
main_output_dir = current_dir / 'output'
main_output_dir.mkdir(exist_ok=True)
# 批量处理所有图像文件
for image_file in image_files:
image_path = str(image_file)
# 创建该图像的子输出目录
img_name = image_file.stem
img_output_dir = main_output_dir / img_name
img_output_dir.mkdir(exist_ok=True)
detect_and_extract_ticket(image_path, output_path=str(img_output_dir))
if __name__ == "__main__":
main()