luozhongze commited on
Commit
210c3af
·
verified ·
1 Parent(s): 97b301f

Upload read_dgrl.py

Browse files
Files changed (1) hide show
  1. read_dgrl.py +125 -0
read_dgrl.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import struct
3
+ from pathlib import Path
4
+ import cv2 as cv
5
+ import numpy as np
6
+ from tqdm import tqdm
7
+
8
+ def read_from_dgrl(dgrl, line_spacing=10):
9
+ if not os.path.exists(dgrl):
10
+ print('DGRL not exists!')
11
+ return
12
+
13
+ dir_name, base_name = os.path.split(dgrl)
14
+ label_dir = dir_name + '_label'
15
+ image_dir = dir_name + '_images'
16
+ if not os.path.exists(label_dir):
17
+ os.makedirs(label_dir)
18
+ if not os.path.exists(image_dir):
19
+ os.makedirs(image_dir)
20
+
21
+ with open(dgrl, 'rb') as f:
22
+ # 读取表头尺寸
23
+ header_size = np.fromfile(f, dtype='uint8', count=4)
24
+ header_size = sum([j << (i*8) for i, j in enumerate(header_size)])
25
+
26
+ # 读取表头剩下内容,提取 code_length
27
+ header = np.fromfile(f, dtype='uint8', count=header_size-4)
28
+ code_length = sum([j << (i*8) for i, j in enumerate(header[-4:-2])])
29
+
30
+ # 读取图像尺寸信息,提取图像中行数量
31
+ image_record = np.fromfile(f, dtype='uint8', count=12)
32
+ height = sum([j << (i*8) for i, j in enumerate(image_record[:4])])
33
+ width = sum([j << (i*8) for i, j in enumerate(image_record[4:8])])
34
+ line_num = sum([j << (i*8) for i, j in enumerate(image_record[8:])])
35
+
36
+ # 初始化存储整张图片和文本的变量,背景设置为白色(255)
37
+ bitmap = np.ones((height + line_num * line_spacing, width), dtype='uint8') * 255
38
+ full_text = ""
39
+
40
+ current_y = 0 # 当前行的Y坐标起始位置
41
+
42
+ # 读取每一行文字的信息
43
+ for k in range(line_num):
44
+ # 读取该行的字符数量
45
+ char_num = np.fromfile(f, dtype='uint8', count=4)
46
+ char_num = sum([j << (i*8) for i, j in enumerate(char_num)])
47
+
48
+ # 读取该行的标注信息
49
+ label = np.fromfile(f, dtype='uint8', count=code_length*char_num)
50
+ label = [label[i] << (8*(i % code_length))
51
+ for i in range(code_length*char_num)]
52
+ label = [sum(label[i*code_length:(i+1)*code_length])
53
+ for i in range(char_num)]
54
+ label = [struct.pack('I', i).decode(
55
+ 'gbk', 'ignore')[0] for i in label]
56
+
57
+ # 合并文本
58
+ label = ''.join(label)
59
+ label = ''.join(label.split(b'\x00'.decode()))
60
+ full_text += label
61
+
62
+ # 读取该行的位置和尺寸
63
+ pos_size = np.fromfile(f, dtype='uint8', count=16)
64
+ y = sum([j << (i*8) for i, j in enumerate(pos_size[:4])])
65
+ x = sum([j << (i*8) for i, j in enumerate(pos_size[4:8])])
66
+ h = sum([j << (i*8) for i, j in enumerate(pos_size[8:12])])
67
+ w = sum([j << (i*8) for i, j in enumerate(pos_size[12:])])
68
+
69
+ # 读取该行的图片
70
+ line_bitmap = np.fromfile(f, dtype='uint8', count=h*w)
71
+ line_bitmap = np.array(line_bitmap).reshape(h, w)
72
+
73
+ # 检查并调整目标区域的大小,避免粘贴出错
74
+ if current_y + h > bitmap.shape[0]:
75
+ h = bitmap.shape[0] - current_y
76
+ if h <= 0:
77
+ print(f"Warning: Insufficient space for line {k+1}. Skipping this line.")
78
+ continue # 跳过当前行,防止粘贴出错
79
+ line_bitmap = line_bitmap[:h, :]
80
+
81
+ # 检查 x 和 w 是否有效
82
+ if x >= bitmap.shape[1]:
83
+ print(f"Warning: Invalid x position for line {k+1}. x={x}, Skipping this line.")
84
+ continue # 跳过当前行
85
+
86
+ if w <= 0:
87
+ print(f"Warning: Width w is zero for line {k+1}. Skipping this line.")
88
+ continue # 跳过当前行
89
+
90
+ if x + w > bitmap.shape[1]:
91
+ w = bitmap.shape[1] - x
92
+ if w <= 0:
93
+ print(f"Warning: Insufficient width for line {k+1}. Skipping this line.")
94
+ continue # 跳过当前行
95
+ line_bitmap = line_bitmap[:, :w]
96
+
97
+ # 打印调试信息
98
+ print(f"Debug: Line {k+1}, x={x}, w={w}, line_bitmap.shape={line_bitmap.shape}")
99
+
100
+ # 粘贴该行图像到整张图片中的对应位置,并增加行间距
101
+ try:
102
+ bitmap[current_y:current_y+h, x:x+w] = line_bitmap[:, :w]
103
+ except ValueError as e:
104
+ print(f"Error while pasting line {k+1}: {e}")
105
+ continue # 跳过当前行,防止因粘贴错误中断整个过程
106
+
107
+ current_y += h + line_spacing
108
+
109
+ # 去除空白部分
110
+ bitmap = bitmap[:current_y, :]
111
+
112
+ # 保存整张图片
113
+ bitmap_file = os.path.join(image_dir, base_name.replace('.dgrl', '.png'))
114
+ cv.imwrite(bitmap_file, bitmap)
115
+
116
+ # 保存合并后的文本段落
117
+ label_file = os.path.join(label_dir, base_name.replace('.dgrl', '.txt'))
118
+ with open(label_file, 'w') as f1:
119
+ f1.write(full_text)
120
+
121
+ if __name__ == '__main__':
122
+ dgrl_paths = Path('/HWDB2.2Test').iterdir()
123
+ dgrl_paths = list(dgrl_paths)
124
+ for dgrl_path in tqdm(dgrl_paths):
125
+ read_from_dgrl(dgrl_path, line_spacing=10)