ndlocr-lite 1.4.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli.py +15 -0
- config/NDLmoji.yaml +4 -0
- config/__init__.py +0 -0
- config/ndl.yaml +21 -0
- deim.py +169 -0
- model/__init__.py +0 -0
- model_download.py +87 -0
- ndl_parser.py +1083 -0
- ndlocr_lite-1.4.0.dev0.dist-info/METADATA +182 -0
- ndlocr_lite-1.4.0.dev0.dist-info/RECORD +43 -0
- ndlocr_lite-1.4.0.dev0.dist-info/WHEEL +5 -0
- ndlocr_lite-1.4.0.dev0.dist-info/entry_points.txt +2 -0
- ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE +395 -0
- ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE_DEPENDENCEIES +1891 -0
- ndlocr_lite-1.4.0.dev0.dist-info/top_level.txt +16 -0
- ndlocr_lite_gui/__init__.py +12 -0
- ndlocr_lite_gui/assets/icon.png +0 -0
- ndlocr_lite_gui/gui_config.py +21 -0
- ndlocr_lite_gui/main.py +2105 -0
- ocr.py +1425 -0
- optional_features/__init__.py +52 -0
- parseq.py +74 -0
- pdf_output_utils.py +71 -0
- reading_order/__init__.py +0 -0
- reading_order/order/__init__.py +0 -0
- reading_order/order/parse_xml.py +143 -0
- reading_order/order/reorder.py +211 -0
- reading_order/order/smooth_order.py +110 -0
- reading_order/order/warichu_block.py +178 -0
- reading_order/order/wrap_dataset.py +13 -0
- reading_order/utils/__init__.py +0 -0
- reading_order/utils/file.py +21 -0
- reading_order/utils/logger.py +29 -0
- reading_order/utils/time.py +63 -0
- reading_order/utils/xml.py +97 -0
- reading_order/xy_cut/__init__.py +0 -0
- reading_order/xy_cut/block_xy_cut.py +366 -0
- reading_order/xy_cut/eval.py +55 -0
- tcy_wrapper.py +202 -0
- tools/ndlkoten2tei.py +115 -0
- uicomponent/localelabel.py +118 -0
- uicomponent/textdaisy.py +1093 -0
- version.py +3 -0
ndl_parser.py
ADDED
|
@@ -0,0 +1,1083 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2023, National Diet Library, Japan
|
|
4
|
+
#
|
|
5
|
+
# This software is released under the CC BY 4.0.
|
|
6
|
+
# https://creativecommons.org/licenses/by/4.0/
|
|
7
|
+
|
|
8
|
+
from typing import List
|
|
9
|
+
from enum import IntEnum, auto
|
|
10
|
+
import sys
|
|
11
|
+
import os
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from lxml import etree as ET
|
|
14
|
+
from tqdm import tqdm
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
class Category(IntEnum):
|
|
18
|
+
TEXT_BLOCK = 0
|
|
19
|
+
LINE_MAIN = auto()
|
|
20
|
+
LINE_CAPTION = auto()
|
|
21
|
+
LINE_AD = auto()
|
|
22
|
+
LINE_NOTE = auto()
|
|
23
|
+
LINE_NOTE_TOCHU = auto()
|
|
24
|
+
|
|
25
|
+
BLOCK_FIG = auto()
|
|
26
|
+
BLOCK_AD = auto()
|
|
27
|
+
BLOCK_PILLAR = auto()
|
|
28
|
+
BLOCK_FOLIO = auto()
|
|
29
|
+
BLOCK_RUBI = auto()
|
|
30
|
+
|
|
31
|
+
BLOCK_CHART = auto()
|
|
32
|
+
BLOCK_EQN = auto()
|
|
33
|
+
BLOCK_CFM = auto()
|
|
34
|
+
BLOCK_ENG = auto()
|
|
35
|
+
|
|
36
|
+
BLOCK_TABLE = auto()
|
|
37
|
+
|
|
38
|
+
LINE_TITLE = auto()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class InlineCategory(IntEnum):
|
|
44
|
+
INLINE_ENG = auto()
|
|
45
|
+
INLINE_RENG = auto()
|
|
46
|
+
INLINE_COLOR = auto()
|
|
47
|
+
INLINE_EQN = auto()
|
|
48
|
+
INLINE_CFM = auto()
|
|
49
|
+
INLINE_HINV = auto()
|
|
50
|
+
INLINE_HAND = auto()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
categories = [
|
|
54
|
+
{'id': int(Category.TEXT_BLOCK), 'name': 'text_block', 'org_name': '本文ブロック'},
|
|
55
|
+
{'id': int(Category.LINE_MAIN), 'name': 'line_main', 'org_name': '本文'},
|
|
56
|
+
{'id': int(Category.LINE_CAPTION), 'name': 'line_caption', 'org_name': 'キャプション'},
|
|
57
|
+
{'id': int(Category.LINE_AD), 'name': 'line_ad', 'org_name': '広告文字'},
|
|
58
|
+
{'id': int(Category.LINE_NOTE), 'name': 'line_note', 'org_name': '割注'},
|
|
59
|
+
{'id': int(Category.LINE_NOTE_TOCHU), 'name': 'line_note_tochu', 'org_name': '頭注'},
|
|
60
|
+
{'id': int(Category.BLOCK_FIG), 'name': 'block_fig', 'org_name': '図版'},
|
|
61
|
+
{'id': int(Category.BLOCK_AD), 'name': 'block_ad', 'org_name': '広告'},
|
|
62
|
+
{'id': int(Category.BLOCK_PILLAR), 'name': 'block_pillar', 'org_name': '柱'},
|
|
63
|
+
{'id': int(Category.BLOCK_FOLIO), 'name': 'block_folio', 'org_name': 'ノンブル'},
|
|
64
|
+
{'id': int(Category.BLOCK_RUBI), 'name': 'block_rubi', 'org_name': 'ルビ'},
|
|
65
|
+
{'id': int(Category.BLOCK_CHART), 'name': 'block_chart', 'org_name': '組織図'},
|
|
66
|
+
{'id': int(Category.BLOCK_EQN), 'name': 'block_eqn', 'org_name': '数式'},
|
|
67
|
+
{'id': int(Category.BLOCK_CFM), 'name': 'block_cfm', 'org_name': '化学式'},
|
|
68
|
+
{'id': int(Category.BLOCK_ENG), 'name': 'block_eng', 'org_name': '欧文'},
|
|
69
|
+
{'id': int(Category.BLOCK_TABLE), 'name': 'block_table', 'org_name': '表組'},
|
|
70
|
+
{'id': int(Category.LINE_TITLE), 'name': 'line_title', 'org_name': 'タイトル本文'},
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
categories_org_name_index = {elem['org_name']: elem for elem in categories}
|
|
74
|
+
categories_name_index = {elem['name']: elem for elem in categories}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def org_name_to_id(s: str):
|
|
78
|
+
return categories_org_name_index[s]['id']
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def name_to_org_name(s: str):
|
|
82
|
+
return categories_name_index[s]['org_name']
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
inline_categories = [
|
|
86
|
+
{'id': int(InlineCategory.INLINE_ENG), 'name': 'inline_eng', 'org_name': '欧文'},
|
|
87
|
+
{'id': int(InlineCategory.INLINE_RENG), 'name': 'inline_reng', 'org_name': '回転欧文'},
|
|
88
|
+
{'id': int(InlineCategory.INLINE_COLOR), 'name': 'inline_color', 'org_name': '色付文字'},
|
|
89
|
+
{'id': int(InlineCategory.INLINE_EQN), 'name': 'inline_eqn', 'org_name': '数式'},
|
|
90
|
+
{'id': int(InlineCategory.INLINE_CFM), 'name': 'inline_cfn', 'org_name': '化学式'},
|
|
91
|
+
{'id': int(InlineCategory.INLINE_HINV), 'name': 'inline_hinv', 'org_name': '縦中横'},
|
|
92
|
+
{'id': int(InlineCategory.INLINE_HAND), 'name': 'inline_hand', 'org_name': '手書き'}]
|
|
93
|
+
|
|
94
|
+
inline_categories_org_name_index = {elem['org_name']: elem for elem in inline_categories}
|
|
95
|
+
inline_categories_name_index = {elem['name']: elem for elem in inline_categories}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
import math
|
|
99
|
+
|
|
100
|
+
def point_in_polygon(point, polygon, measureDist=False):
|
|
101
|
+
def point_line_distance(px, py, x1, y1, x2, y2):
|
|
102
|
+
""" Calculate the minimum distance from point to line segment. """
|
|
103
|
+
line_len_square = (x2 - x1) ** 2 + (y2 - y1) ** 2
|
|
104
|
+
if line_len_square == 0:
|
|
105
|
+
return math.hypot(px - x1, py - y1)
|
|
106
|
+
t = ((px - x1) * (x2 - x1) + (py - y1) * (y2 - y1)) / line_len_square
|
|
107
|
+
t = max(0, min(1, t))
|
|
108
|
+
projection_x = x1 + t * (x2 - x1)
|
|
109
|
+
projection_y = y1 + t * (y2 - y1)
|
|
110
|
+
return math.hypot(px - projection_x, py - projection_y)
|
|
111
|
+
polygon=np.squeeze(polygon)
|
|
112
|
+
#print(point,polygon)
|
|
113
|
+
x, y = point
|
|
114
|
+
n = len(polygon)
|
|
115
|
+
inside = False
|
|
116
|
+
min_dist = float('inf')
|
|
117
|
+
|
|
118
|
+
px, py = polygon[0]
|
|
119
|
+
for i in range(1, n + 1):
|
|
120
|
+
sx, sy = polygon[i % n]
|
|
121
|
+
if min(py, sy) < y <= max(py, sy) and x <= max(px, sx):
|
|
122
|
+
if py != sy:
|
|
123
|
+
xinters = (y - py) * (sx - px) / (sy - py) + px
|
|
124
|
+
if px == sx or x <= xinters:
|
|
125
|
+
inside = not inside
|
|
126
|
+
if measureDist:
|
|
127
|
+
dist = point_line_distance(x, y, px, py, sx, sy)
|
|
128
|
+
if dist < min_dist:
|
|
129
|
+
min_dist = dist
|
|
130
|
+
px, py = sx, sy
|
|
131
|
+
|
|
132
|
+
# Check if the point is on the boundary of the polygon
|
|
133
|
+
for i in range(n):
|
|
134
|
+
sx, sy = polygon[i]
|
|
135
|
+
ex, ey = polygon[(i + 1) % n]
|
|
136
|
+
if (sy == ey and sy == y and min(sx, ex) <= x <= max(sx, ex)) or \
|
|
137
|
+
(sx == ex and sx == x and min(sy, ey) <= y <= max(sy, ey)):
|
|
138
|
+
return 0 if not measureDist else 0.0
|
|
139
|
+
|
|
140
|
+
if measureDist:
|
|
141
|
+
return min_dist if inside else -min_dist
|
|
142
|
+
return 1 if inside else -1
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def inline_org_name_to_id(s: str):
|
|
146
|
+
return inline_categories_org_name_index[s]['id']
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def inline_name_to_org_name(s: str):
|
|
150
|
+
return inline_categories_name_index[s]['org_name']
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class NDLObject:
|
|
154
|
+
def __init__(self, x, y, width, height, category_id=-1):
|
|
155
|
+
self.x, self.y = x, y
|
|
156
|
+
self.width, self.height = width, height
|
|
157
|
+
self.category_id = category_id
|
|
158
|
+
|
|
159
|
+
def __repr__(self):
|
|
160
|
+
return f'NDLObject({self.x}, {self.y}, {self.width}, {self.height}, category_id={self.category_id})'
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class NDLBlock(NDLObject):
|
|
164
|
+
def __init__(self, type, *args, **kwargs):
|
|
165
|
+
super().__init__(*args, **kwargs)
|
|
166
|
+
self.category_id = org_name_to_id(type)
|
|
167
|
+
self.type = type
|
|
168
|
+
|
|
169
|
+
def __repr__(self):
|
|
170
|
+
return f'NDLBlock({self.type}, {self.x}, {self.y}, {self.width}, {self.height}, category_id={self.category_id})'
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class NDLChar(NDLObject):
|
|
174
|
+
def __init__(self, moji: str, *args, **kwargs):
|
|
175
|
+
super().__init__(*args, **kwargs)
|
|
176
|
+
self.moji = moji
|
|
177
|
+
self.category_id = Category.CHAR
|
|
178
|
+
|
|
179
|
+
def __repr__(self):
|
|
180
|
+
return f'NDLChar(\'{self.moji}\', {self.x}, {self.y}, {self.width}, {self.height}, category_id={self.category_id})'
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class NDLInline(NDLObject):
|
|
184
|
+
def __init__(self, type, *args, **kwargs):
|
|
185
|
+
super().__init__(*args, **kwargs)
|
|
186
|
+
self.category_id = inline_org_name_to_id(type)
|
|
187
|
+
self.type = type
|
|
188
|
+
|
|
189
|
+
def __repr(self):
|
|
190
|
+
return f'NDLInline({self.type}, {self.x}, {self.y}, {self.width}, {self.height}, category_id={self.category_id})'
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class NDLLine(NDLObject):
|
|
194
|
+
def __init__(self, chars: List[NDLChar], opt: str, *args, **kwargs):
|
|
195
|
+
super().__init__(*args, **kwargs)
|
|
196
|
+
self.chars = chars
|
|
197
|
+
self.category_id = org_name_to_id(opt)
|
|
198
|
+
self.opt = opt
|
|
199
|
+
|
|
200
|
+
def __repr__(self):
|
|
201
|
+
return f'NDLLine({self.chars}, {self.opt}, {self.x}, {self.y}, {self.width}, {self.height}, category_id={self.category_id})'
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class NDLTextblock(NDLObject):
|
|
205
|
+
def __init__(self, points, opt: str, *args, **kwargs):
|
|
206
|
+
super().__init__(*args, **kwargs)
|
|
207
|
+
self.category_id = org_name_to_id(opt)
|
|
208
|
+
self.type = opt
|
|
209
|
+
self.points = points
|
|
210
|
+
|
|
211
|
+
def __repr__(self):
|
|
212
|
+
return f'NDLTextblock({self.type}, {self.x}, {self.y}, {self.width}, {self.height}, category_id={self.category_id})'
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class NDLPage:
|
|
216
|
+
def __init__(self, img_path: str, objects: List[NDLObject], source_xml: str):
|
|
217
|
+
self.img_path = img_path
|
|
218
|
+
self.objects = objects
|
|
219
|
+
self.source_xml = source_xml
|
|
220
|
+
|
|
221
|
+
def __repr__(self):
|
|
222
|
+
return f'NDLPage({self.img_path}, {self.objects}, {self.source_xml})'
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
class NDLDataset:
|
|
226
|
+
def __init__(self, pages=None):
|
|
227
|
+
self.pages = [] if pages is None else pages
|
|
228
|
+
|
|
229
|
+
def parse(self, xml_path: str, img_dir: str):
|
|
230
|
+
import xml.etree.ElementTree as ET
|
|
231
|
+
from pathlib import Path
|
|
232
|
+
|
|
233
|
+
print(f'loading from {xml_path} ... ', end='')
|
|
234
|
+
|
|
235
|
+
tree = ET.parse(xml_path)
|
|
236
|
+
root = tree.getroot()
|
|
237
|
+
pages = []
|
|
238
|
+
|
|
239
|
+
def parse_bbox(elem):
|
|
240
|
+
return float(elem.attrib['X']), float(elem.attrib['Y']), float(elem.attrib['WIDTH']), float(elem.attrib['HEIGHT'])
|
|
241
|
+
|
|
242
|
+
def get_tag(elem):
|
|
243
|
+
prefix, has_namespace, postfix = elem.tag.partition('}')
|
|
244
|
+
if has_namespace:
|
|
245
|
+
tag = postfix
|
|
246
|
+
else:
|
|
247
|
+
tag = child_elem.tag
|
|
248
|
+
return tag
|
|
249
|
+
|
|
250
|
+
def parse_points(elem):
|
|
251
|
+
points_str = elem[0].attrib['POINTS']
|
|
252
|
+
points_list = [float(i) for i in points_str.split(',')]
|
|
253
|
+
return points_list
|
|
254
|
+
|
|
255
|
+
def points_to_bbox(points_list):
|
|
256
|
+
if len(points_list) % 2 == 1:
|
|
257
|
+
print("ERROR: Invalid polygon points")
|
|
258
|
+
return 0, 0, 0, 0
|
|
259
|
+
it = iter(points_list)
|
|
260
|
+
min_x = points_list[0]
|
|
261
|
+
min_y = points_list[1]
|
|
262
|
+
max_x = 0
|
|
263
|
+
max_y = 0
|
|
264
|
+
for i in range(2, len(it), 2):
|
|
265
|
+
tx = it[i]
|
|
266
|
+
ty = it[i+1]
|
|
267
|
+
if min_x > tx:
|
|
268
|
+
min_x = tx
|
|
269
|
+
if max_x < tx:
|
|
270
|
+
max_x = tx
|
|
271
|
+
if min_y > ty:
|
|
272
|
+
min_y = ty
|
|
273
|
+
if max_y < ty:
|
|
274
|
+
max_y = ty
|
|
275
|
+
return min_x, min_y, (max_x-min_x), (max_y-min_y)
|
|
276
|
+
|
|
277
|
+
def parse_textblock(elem, objects, ad=False):
|
|
278
|
+
for child_elem in elem:
|
|
279
|
+
prefix, has_namespace, postfix = child_elem.tag.partition('}')
|
|
280
|
+
if has_namespace:
|
|
281
|
+
tag = postfix
|
|
282
|
+
else:
|
|
283
|
+
tag = child_elem.tag
|
|
284
|
+
|
|
285
|
+
if tag == 'SHAPE': # SHAPE info in TEXT_BLOCK
|
|
286
|
+
points = parse_points(child_elem)
|
|
287
|
+
bbox = points_to_bbox(points)
|
|
288
|
+
opt = '本文ブロック'
|
|
289
|
+
if ad:
|
|
290
|
+
opt = '広告本文ブロック'
|
|
291
|
+
objects.append(
|
|
292
|
+
NDLTextblock(points, opt, *bbox))
|
|
293
|
+
elif tag == 'LINE': # LINE in TEXT_BLOCK
|
|
294
|
+
chars = []
|
|
295
|
+
bbox = parse_bbox(child_elem)
|
|
296
|
+
for char in child_elem:
|
|
297
|
+
bbox_char = parse_bbox(char)
|
|
298
|
+
if get_tag(char) != 'CHAR': # INLINE
|
|
299
|
+
print(char.attrib['TYPE'])
|
|
300
|
+
chars.append(NDLInline(char.attrib['TYPE'], *bbox_char))
|
|
301
|
+
else: # CHAR
|
|
302
|
+
chars.append(NDLChar(char.attrib['MOJI'], *bbox_char))
|
|
303
|
+
objects.append(
|
|
304
|
+
NDLLine(chars, child_elem.attrib.get('TYPE', ''), *bbox))
|
|
305
|
+
else:
|
|
306
|
+
continue
|
|
307
|
+
|
|
308
|
+
for page in root:
|
|
309
|
+
img_path = str(Path(img_dir) / page.attrib['IMAGENAME'])
|
|
310
|
+
objects = []
|
|
311
|
+
# print('\n**len {}'.format(len(page)))
|
|
312
|
+
for elem in page:
|
|
313
|
+
prefix, has_namespace, postfix = elem.tag.partition('}')
|
|
314
|
+
if has_namespace:
|
|
315
|
+
tag = postfix
|
|
316
|
+
else:
|
|
317
|
+
tag = elem.tag
|
|
318
|
+
|
|
319
|
+
if elem.get('ERROR') is not None:
|
|
320
|
+
print('ERROR attrib is found!!!!')
|
|
321
|
+
print('skip the element')
|
|
322
|
+
continue
|
|
323
|
+
|
|
324
|
+
if tag == 'BLOCK':
|
|
325
|
+
bbox = parse_bbox(elem)
|
|
326
|
+
objects.append(NDLBlock(elem.attrib['TYPE'], *bbox))
|
|
327
|
+
if elem.attrib['TYPE'] == '広告':
|
|
328
|
+
print("parse_ad")
|
|
329
|
+
for child_elem in elem:
|
|
330
|
+
if get_tag(child_elem) == 'TEXTBLOCK':
|
|
331
|
+
parse_textblock(child_elem, objects, ad=True)
|
|
332
|
+
|
|
333
|
+
elif tag == 'LINE':
|
|
334
|
+
chars = []
|
|
335
|
+
bbox = parse_bbox(elem)
|
|
336
|
+
for char in elem:
|
|
337
|
+
bbox_char = parse_bbox(char)
|
|
338
|
+
if get_tag(char) != 'CHAR': # INLINE
|
|
339
|
+
print(char.attrib['TYPE'])
|
|
340
|
+
chars.append(NDLInline(char.attrib['TYPE'], *bbox_char))
|
|
341
|
+
else: # CHAR
|
|
342
|
+
chars.append(NDLChar(char.attrib['MOJI'], *bbox_char))
|
|
343
|
+
objects.append(
|
|
344
|
+
NDLLine(chars, elem.attrib.get('TYPE', ''), *bbox))
|
|
345
|
+
elif tag == 'TEXTBLOCK':
|
|
346
|
+
parse_textblock(elem, objects)
|
|
347
|
+
else:
|
|
348
|
+
pass
|
|
349
|
+
pages.append(NDLPage(img_path, objects, Path(xml_path).stem))
|
|
350
|
+
print(f'done! {len(pages)} loaded')
|
|
351
|
+
self.pages.extend(pages)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def summary(self, output_dir: str = "./generated/"):
|
|
355
|
+
import numpy as np
|
|
356
|
+
import matplotlib.pyplot as plt
|
|
357
|
+
from collections import defaultdict
|
|
358
|
+
sizes = []
|
|
359
|
+
bbox_nums = []
|
|
360
|
+
opts = defaultdict(int)
|
|
361
|
+
types = defaultdict(int)
|
|
362
|
+
for page in self.pages:
|
|
363
|
+
cnt = 0
|
|
364
|
+
for obj in page.objects:
|
|
365
|
+
sizes.append(
|
|
366
|
+
np.array([obj.width, obj.height], dtype=np.float32))
|
|
367
|
+
if isinstance(obj, NDLBlock):
|
|
368
|
+
types[obj.type] += 1
|
|
369
|
+
cnt += 1
|
|
370
|
+
if isinstance(obj, NDLLine):
|
|
371
|
+
cnt += len(obj.chars)
|
|
372
|
+
opts[obj.opt] += 1
|
|
373
|
+
bbox_nums.append(cnt)
|
|
374
|
+
|
|
375
|
+
print(opts)
|
|
376
|
+
print(types)
|
|
377
|
+
|
|
378
|
+
sizes = np.array(sizes)
|
|
379
|
+
bbox_nums = np.array(bbox_nums)
|
|
380
|
+
|
|
381
|
+
def savefig(data, file_name):
|
|
382
|
+
plt.figure()
|
|
383
|
+
plt.hist(data)
|
|
384
|
+
plt.savefig(output_dir + file_name)
|
|
385
|
+
|
|
386
|
+
savefig(sizes[:, 0], "hist_width.png")
|
|
387
|
+
savefig(sizes[:, 1], "hist_height.png")
|
|
388
|
+
savefig(sizes[:, 1] / sizes[:, 0], "hist_aspect.png")
|
|
389
|
+
savefig(bbox_nums, "hist_bbox_num.png")
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def to_coco_fmt(self, fx=1.0, fy=1.0, add_char: bool = True, add_block: bool = True, add_prefix: bool = False, suffix: str = ".jpg"):
|
|
393
|
+
import cv2
|
|
394
|
+
import numpy as np
|
|
395
|
+
from pathlib import Path
|
|
396
|
+
from tqdm import tqdm
|
|
397
|
+
from collections import defaultdict
|
|
398
|
+
output = {'images': [], 'annotations': []}
|
|
399
|
+
image_id = 0
|
|
400
|
+
annotation_id = 0
|
|
401
|
+
instance_num = defaultdict(int)
|
|
402
|
+
|
|
403
|
+
print("start to_coco_fmt")
|
|
404
|
+
|
|
405
|
+
def make_bbox(obj):
|
|
406
|
+
x1, y1 = fx * obj.x, fy * obj.y
|
|
407
|
+
width, height = fx * obj.width, fy * obj.height
|
|
408
|
+
x2, y2 = x1 + width, y1 + height
|
|
409
|
+
bbox = [x1, y1, width, height]
|
|
410
|
+
area = width * height
|
|
411
|
+
contour = [x1, y1, x2, y1, x2, y2, x1, y2]
|
|
412
|
+
return bbox, contour, area
|
|
413
|
+
|
|
414
|
+
def make_contours(obj):
|
|
415
|
+
x1, y1 = fx * obj.x, fy * obj.y
|
|
416
|
+
width, height = fx * obj.width, fy * obj.height
|
|
417
|
+
bbox = [x1, y1, width, height]
|
|
418
|
+
it = iter(obj.points)
|
|
419
|
+
cv_contours = []
|
|
420
|
+
for tx, ty in zip(*[it]*2):
|
|
421
|
+
tmp = np.array([tx, ty], dtype='float32')
|
|
422
|
+
cv_contours.append(tmp)
|
|
423
|
+
area = cv2.contourArea(np.array(cv_contours))
|
|
424
|
+
contour = obj.points
|
|
425
|
+
return bbox, contour, area
|
|
426
|
+
|
|
427
|
+
def add_annotation(obj):
|
|
428
|
+
bbox, contour, area = make_bbox(obj)
|
|
429
|
+
ann = {'image_id': image_id, 'id': annotation_id, 'bbox': bbox, 'area': area,
|
|
430
|
+
'iscrowd': 0, 'category_id': int(obj.category_id)}
|
|
431
|
+
ann['segmentation'] = [contour]
|
|
432
|
+
output['annotations'].append(ann)
|
|
433
|
+
|
|
434
|
+
def add_line_annotation(obj):
|
|
435
|
+
bbox, _, area_sum = make_bbox(obj)
|
|
436
|
+
area = 0
|
|
437
|
+
contours = []
|
|
438
|
+
|
|
439
|
+
# chars as line
|
|
440
|
+
_, contour, area = make_bbox(obj)
|
|
441
|
+
contours.append(contour)
|
|
442
|
+
if area == 0:
|
|
443
|
+
area = area_sum
|
|
444
|
+
|
|
445
|
+
ann = {'image_id': image_id, 'id': annotation_id, 'bbox': bbox, 'area': area,
|
|
446
|
+
'iscrowd': 0, 'category_id': int(obj.category_id)}
|
|
447
|
+
ann['segmentation'] = contours
|
|
448
|
+
output['annotations'].append(ann)
|
|
449
|
+
|
|
450
|
+
def add_textblock_annotation(obj):
|
|
451
|
+
bbox, contour, area = make_contours(obj)
|
|
452
|
+
ann = {'image_id': image_id, 'id': annotation_id, 'bbox': bbox, 'area': area,
|
|
453
|
+
'iscrowd': 0, 'category_id': int(obj.category_id)}
|
|
454
|
+
ann['segmentation'] = [contour]
|
|
455
|
+
output['annotations'].append(ann)
|
|
456
|
+
|
|
457
|
+
for page in tqdm(self.pages):
|
|
458
|
+
img = cv2.imread(page.img_path)
|
|
459
|
+
if img is None:
|
|
460
|
+
print(f"Cannot load {page.img_path}")
|
|
461
|
+
continue
|
|
462
|
+
|
|
463
|
+
prefix = page.source_xml + "_" if add_prefix else ""
|
|
464
|
+
file_name = prefix + str(Path(page.img_path).name)
|
|
465
|
+
if Path(file_name).suffix != suffix:
|
|
466
|
+
file_name = str(Path(file_name).with_suffix('.jpg'))
|
|
467
|
+
image = {'file_name': file_name,
|
|
468
|
+
'width': int(fx * img.shape[1]), 'height': int(fy * img.shape[0]), "id": image_id}
|
|
469
|
+
output['images'].append(image)
|
|
470
|
+
for obj in page.objects:
|
|
471
|
+
if add_block:
|
|
472
|
+
if isinstance(obj, NDLLine):
|
|
473
|
+
add_line_annotation(obj)
|
|
474
|
+
elif isinstance(obj, NDLTextblock):
|
|
475
|
+
add_textblock_annotation(obj)
|
|
476
|
+
else: # BLOCK
|
|
477
|
+
add_annotation(obj)
|
|
478
|
+
instance_num[int(obj.category_id)] += 1
|
|
479
|
+
annotation_id += 1
|
|
480
|
+
|
|
481
|
+
image_id += 1
|
|
482
|
+
|
|
483
|
+
print(instance_num)
|
|
484
|
+
|
|
485
|
+
output['categories'] = categories
|
|
486
|
+
output['info'] = {
|
|
487
|
+
"description": "NDL",
|
|
488
|
+
"url": "",
|
|
489
|
+
"version": "0.1a",
|
|
490
|
+
"year": 2021,
|
|
491
|
+
"contributor": "morpho",
|
|
492
|
+
"date_created": "2021/09/01"
|
|
493
|
+
}
|
|
494
|
+
output['licenses'] = []
|
|
495
|
+
return output
|
|
496
|
+
|
|
497
|
+
def train_test_split(self, ratio: float = 0.9):
|
|
498
|
+
import random
|
|
499
|
+
from copy import deepcopy
|
|
500
|
+
print("start train_test_split")
|
|
501
|
+
pages = deepcopy(self.pages)
|
|
502
|
+
random.shuffle(pages)
|
|
503
|
+
split = int(ratio * len(pages))
|
|
504
|
+
return NDLDataset(pages[:split]), NDLDataset(pages[split:])
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def json_to_file(data, output_path: str):
|
|
508
|
+
import json
|
|
509
|
+
with open(output_path, 'w') as f:
|
|
510
|
+
json.dump(data, f, indent=4)
|
|
511
|
+
|
|
512
|
+
def textblock_to_polygon(classes, res_segm, min_bbox_size=5):
|
|
513
|
+
import cv2
|
|
514
|
+
import numpy as np
|
|
515
|
+
|
|
516
|
+
tb_cls_id = classes.index('text_block')
|
|
517
|
+
polygons = []
|
|
518
|
+
|
|
519
|
+
for segm in res_segm[tb_cls_id]:
|
|
520
|
+
mask_img = segm.astype(np.uint8)
|
|
521
|
+
contours, _ = cv2.findContours(mask_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 輪郭、階層の抽出
|
|
522
|
+
if len(contours)==0: # 領域が存在しないケース
|
|
523
|
+
polygons.append(None)
|
|
524
|
+
continue
|
|
525
|
+
|
|
526
|
+
# 領域が存在するケース
|
|
527
|
+
# 複数のcontourに分裂している場合、頂点数の多いもののみを主領域として採用する。 # method4とする
|
|
528
|
+
main_contours_id = 0
|
|
529
|
+
for i in range(len(contours)):
|
|
530
|
+
if len(contours[i]) > len(contours[main_contours_id]):
|
|
531
|
+
main_contours_id = i
|
|
532
|
+
if len(contours[main_contours_id])<4:
|
|
533
|
+
# 主領域が小さい場合、領域は存在しないものとして除外
|
|
534
|
+
polygons.append(None)
|
|
535
|
+
continue
|
|
536
|
+
arclen = cv2.arcLength(contours[main_contours_id], True)
|
|
537
|
+
app_cnt = cv2.approxPolyDP(contours[main_contours_id], epsilon=0.001 * arclen, closed=True)
|
|
538
|
+
_, _, w, h = make_bbox_from_poly(app_cnt)
|
|
539
|
+
if w < min_bbox_size and h < min_bbox_size:
|
|
540
|
+
continue
|
|
541
|
+
polygons.append(app_cnt)
|
|
542
|
+
|
|
543
|
+
return polygons
|
|
544
|
+
|
|
545
|
+
def textblock_to_rect(classes, res_textboxes, min_bbox_size=5):
|
|
546
|
+
#import cv2
|
|
547
|
+
import numpy as np
|
|
548
|
+
|
|
549
|
+
rect_polygons = []
|
|
550
|
+
for res_textbox in res_textboxes[0]:
|
|
551
|
+
#print(res_textbox)
|
|
552
|
+
xmin,ymin,xmax,ymax=res_textbox
|
|
553
|
+
if xmax-xmin < min_bbox_size and ymax-ymin < min_bbox_size:
|
|
554
|
+
continue
|
|
555
|
+
#polygon = np.array([[[xmin,ymin]], [[xmax,ymin]], [[xmin,ymax]], [[xmax,ymax]]], dtype=np.int32)
|
|
556
|
+
polygon = np.array([[[xmin,ymin]], [[xmin,ymax]], [[xmax,ymax]], [[xmax,ymin]]], dtype=np.int32)
|
|
557
|
+
rect_polygons.append(polygon)
|
|
558
|
+
return rect_polygons
|
|
559
|
+
|
|
560
|
+
def add_text_block_head(s, poly, conf=0.0, indent=''):
|
|
561
|
+
s += indent + f'<TEXTBLOCK CONF = "{conf:0.3f}">\n'
|
|
562
|
+
s += indent + ' ' + '<SHAPE><POLYGON POINTS = "'
|
|
563
|
+
for id_poly, pt in enumerate(poly):
|
|
564
|
+
if id_poly > 0:
|
|
565
|
+
s += f',{pt[0][0]},{pt[0][1]}'
|
|
566
|
+
else:
|
|
567
|
+
s += f'{pt[0][0]},{pt[0][1]}'
|
|
568
|
+
s += '"/></SHAPE>\n'
|
|
569
|
+
return s
|
|
570
|
+
|
|
571
|
+
|
|
572
|
+
def add_block_ad_head(s, block_ad, conf=0.0):
|
|
573
|
+
# block_ad [x1, y1, x2, y2, score]
|
|
574
|
+
x, y = int(block_ad[0]), int(block_ad[1])
|
|
575
|
+
w, h = int(block_ad[2] - block_ad[0]), int(block_ad[3] - block_ad[1])
|
|
576
|
+
s += f'<BLOCK TYPE="広告" X="{x}" Y="{y}" WIDTH="{w}" HEIGHT="{h}" CONF = "{conf:0.3f}">\n'
|
|
577
|
+
return s
|
|
578
|
+
|
|
579
|
+
def add_block_table_head(s, block_table, conf=0.0):
|
|
580
|
+
x, y = int(block_table[0]), int(block_table[1])
|
|
581
|
+
w, h = int(block_table[2] - block_table[0]), int(block_table[3] - block_table[1])
|
|
582
|
+
s += f'<BLOCK TYPE="表組" X="{x}" Y="{y}" WIDTH="{w}" HEIGHT="{h}" CONF = "{conf:0.3f}">\n'
|
|
583
|
+
return s
|
|
584
|
+
|
|
585
|
+
def make_bbox_from_poly(poly):
|
|
586
|
+
x1, y1 = poly[0][0][0], poly[0][0][1]
|
|
587
|
+
x2, y2 = poly[0][0][0], poly[0][0][1]
|
|
588
|
+
for pt in poly[1:]:
|
|
589
|
+
x1 = min(x1, pt[0][0])
|
|
590
|
+
y1 = min(y1, pt[0][1])
|
|
591
|
+
x2 = max(x2, pt[0][0])
|
|
592
|
+
y2 = max(y2, pt[0][1])
|
|
593
|
+
|
|
594
|
+
return x1, y1, (x2-x1), (y2-y1)
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def is_in_block_ad(block_ad, poly):
|
|
598
|
+
if str(type(poly[0])) == "<class 'numpy.ndarray'>":
|
|
599
|
+
x1, y1 = poly[0][0][0], poly[0][0][1]
|
|
600
|
+
x2, y2 = poly[0][0][0], poly[0][0][1]
|
|
601
|
+
for pt in poly[1:]:
|
|
602
|
+
x1 = min(x1, pt[0][0])
|
|
603
|
+
y1 = min(y1, pt[0][1])
|
|
604
|
+
x2 = max(x2, pt[0][0])
|
|
605
|
+
y2 = max(y2, pt[0][1])
|
|
606
|
+
else: # when poly is bbox
|
|
607
|
+
x1, y1, x2, y2 = int(poly[0]), int(poly[1]), int(poly[2]), int(poly[3])
|
|
608
|
+
cx = (x1+x2)//2
|
|
609
|
+
cy = (y1+y2)//2
|
|
610
|
+
#print(block_ad)
|
|
611
|
+
# block_ad [x1, y1, x2, y2, score]
|
|
612
|
+
if block_ad[0] <= cx and cx <= block_ad[2] and block_ad[1] <= cy and cy <= block_ad[3]:
|
|
613
|
+
#print(x1, y1, x2, y2,block_ad)
|
|
614
|
+
return True
|
|
615
|
+
else:
|
|
616
|
+
return False
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def set_elm_detail(elm, bbox):
|
|
620
|
+
elm.set('X', str(int(bbox[0])))
|
|
621
|
+
elm.set('Y', str(int(bbox[1])))
|
|
622
|
+
elm.set('WIDTH', str(int(bbox[2]-bbox[0])))
|
|
623
|
+
elm.set('HEIGHT', str(int(bbox[3]-bbox[1])))
|
|
624
|
+
elm.set('CONF', f'{bbox[4]:0.3f}')
|
|
625
|
+
return
|
|
626
|
+
|
|
627
|
+
# Remove overlappiong polygons
|
|
628
|
+
def refine_tb_polygons(polygons, margin: int = 50):
|
|
629
|
+
import cv2
|
|
630
|
+
from copy import deepcopy
|
|
631
|
+
res_polygons = deepcopy(polygons)
|
|
632
|
+
|
|
633
|
+
for i, child_poly in enumerate(res_polygons):
|
|
634
|
+
if child_poly is None:
|
|
635
|
+
continue
|
|
636
|
+
for j, parent_poly in enumerate(res_polygons):
|
|
637
|
+
if i==j: # The child and parent are the same polygon
|
|
638
|
+
continue
|
|
639
|
+
if parent_poly is None:
|
|
640
|
+
continue
|
|
641
|
+
all_points_is_in = True
|
|
642
|
+
for p in child_poly:
|
|
643
|
+
x = int(p[0][0])
|
|
644
|
+
y = int(p[0][1])
|
|
645
|
+
#if cv2.pointPolygonTest(parent_poly, (x, y), True) < -margin: # > 0 means in
|
|
646
|
+
if point_in_polygon((int(x), int(y)),parent_poly, False)< -margin:
|
|
647
|
+
all_points_is_in = False
|
|
648
|
+
|
|
649
|
+
if all_points_is_in:
|
|
650
|
+
res_polygons[i] = None
|
|
651
|
+
break
|
|
652
|
+
|
|
653
|
+
return res_polygons
|
|
654
|
+
|
|
655
|
+
def get_relationship(res_bbox, tb_polygons, classes, use_block_ad: bool = True, score_thr: float = 0.3):
|
|
656
|
+
#import cv2
|
|
657
|
+
tb_cls_id = classes.index('text_block')
|
|
658
|
+
tb_info = [[] for i in range(len(tb_polygons))]
|
|
659
|
+
independ_lines = []
|
|
660
|
+
|
|
661
|
+
ad_info = None
|
|
662
|
+
if use_block_ad:
|
|
663
|
+
ba_cls_id = classes.index('block_ad')
|
|
664
|
+
ad_info = [[] for i in range(len(res_bbox[ba_cls_id]))]
|
|
665
|
+
|
|
666
|
+
if use_block_ad:
|
|
667
|
+
for i, poly in enumerate(tb_polygons):
|
|
668
|
+
if res_bbox[tb_cls_id][i][4] < score_thr or tb_polygons[i] is None:
|
|
669
|
+
tb_info[i] = None
|
|
670
|
+
continue
|
|
671
|
+
for j, block_ad in enumerate(res_bbox[ba_cls_id]):
|
|
672
|
+
if res_bbox[ba_cls_id][j][4] < score_thr:
|
|
673
|
+
ad_info[j] = None
|
|
674
|
+
continue
|
|
675
|
+
if is_in_block_ad(block_ad, poly):
|
|
676
|
+
ad_info[j].append([tb_cls_id, i])
|
|
677
|
+
break
|
|
678
|
+
|
|
679
|
+
for c in range(len(classes)):
|
|
680
|
+
cls = classes[c]
|
|
681
|
+
if not cls.startswith('line_'):
|
|
682
|
+
continue
|
|
683
|
+
for j, line in enumerate(res_bbox[c]):
|
|
684
|
+
if float(line[4]) < score_thr:
|
|
685
|
+
continue
|
|
686
|
+
in_any_block = False
|
|
687
|
+
# elems belonging to text_block
|
|
688
|
+
for i, poly in enumerate(tb_polygons):
|
|
689
|
+
if res_bbox[tb_cls_id][i][4] < score_thr or tb_polygons[i] is None:
|
|
690
|
+
tb_info[i] = None
|
|
691
|
+
continue
|
|
692
|
+
cx, cy = (line[0]+line[2])//2, (line[1]+line[3])//2
|
|
693
|
+
|
|
694
|
+
#if cv2.pointPolygonTest(poly, (cx, cy), False) > 0:
|
|
695
|
+
if point_in_polygon( (int(cx), int(cy)),poly,False)>=0:
|
|
696
|
+
tb_info[i].append([c, j])
|
|
697
|
+
in_any_block = True
|
|
698
|
+
break
|
|
699
|
+
# elems belonging to ad_block
|
|
700
|
+
if not in_any_block:
|
|
701
|
+
for i, block_ad in enumerate(res_bbox[ba_cls_id]):
|
|
702
|
+
if ad_info[i] is None:
|
|
703
|
+
continue
|
|
704
|
+
if is_in_block_ad(block_ad, line):
|
|
705
|
+
ad_info[i].append([c, j])
|
|
706
|
+
in_any_block = True
|
|
707
|
+
break
|
|
708
|
+
# Line elements not belonging to any text_block or ad_block
|
|
709
|
+
if not in_any_block:
|
|
710
|
+
independ_lines.append([c, j])
|
|
711
|
+
|
|
712
|
+
return tb_info, ad_info, independ_lines
|
|
713
|
+
|
|
714
|
+
def get_relationship_rect(res_bbox, tb_polygons, classes, use_block_ad: bool = True, score_thr: float = 0.1):
|
|
715
|
+
#import cv2
|
|
716
|
+
tb_cls_id = classes.index('text_block')
|
|
717
|
+
ba_cls_id = classes.index('block_ad')
|
|
718
|
+
table_cls_id = classes.index('block_table')
|
|
719
|
+
tb_info = [[] for i in range(len(tb_polygons))]
|
|
720
|
+
independ_lines = []
|
|
721
|
+
table_info=[[] for i in range(len(res_bbox[table_cls_id]))]
|
|
722
|
+
ad_info = [[] for i in range(len(res_bbox[ba_cls_id]))]
|
|
723
|
+
for c in range(len(classes)):
|
|
724
|
+
cls = classes[c]
|
|
725
|
+
if not cls.startswith('line_'):
|
|
726
|
+
continue
|
|
727
|
+
for j, line in enumerate(res_bbox[c]):
|
|
728
|
+
|
|
729
|
+
if float(line[4]) < score_thr:
|
|
730
|
+
continue
|
|
731
|
+
in_any_block = False
|
|
732
|
+
# elems belonging to text_block
|
|
733
|
+
for i, poly in enumerate(tb_polygons):
|
|
734
|
+
if tb_polygons[i] is None:
|
|
735
|
+
tb_info[i] = None
|
|
736
|
+
continue
|
|
737
|
+
cx, cy = (line[0]+line[2])//2, (line[1]+line[3])//2
|
|
738
|
+
poly=np.array([p[0] for p in poly])
|
|
739
|
+
#print(poly)
|
|
740
|
+
#if cv2.pointPolygonTest(poly, (int(cx), int(cy)), False) >= 0:
|
|
741
|
+
if point_in_polygon((int(cx), int(cy)),poly,False)>=0:
|
|
742
|
+
tb_info[i].append([c, j])
|
|
743
|
+
in_any_block = True
|
|
744
|
+
break
|
|
745
|
+
# elems belonging to ad_block
|
|
746
|
+
if not in_any_block:
|
|
747
|
+
for i, block_ad in enumerate(res_bbox[ba_cls_id]):
|
|
748
|
+
if is_in_block_ad(block_ad, line):
|
|
749
|
+
ad_info[i].append([c, j])
|
|
750
|
+
in_any_block = True
|
|
751
|
+
break
|
|
752
|
+
if not in_any_block:
|
|
753
|
+
for i, block_table in enumerate(res_bbox[table_cls_id]):
|
|
754
|
+
if is_in_block_ad(block_table, line):
|
|
755
|
+
table_info[i].append([c, j])
|
|
756
|
+
in_any_block = True
|
|
757
|
+
break
|
|
758
|
+
# Line elements not belonging to any text_block or ad_block
|
|
759
|
+
if not in_any_block:
|
|
760
|
+
independ_lines.append([c, j])
|
|
761
|
+
return tb_info, ad_info,table_info, independ_lines
|
|
762
|
+
|
|
763
|
+
def refine_tb_relationship(tb_polygons, tb_info, classes, margin: int = 50):
|
|
764
|
+
#import cv2
|
|
765
|
+
tb_cls_id = classes.index('text_block')
|
|
766
|
+
|
|
767
|
+
for c_index, child_poly in enumerate(tb_polygons):
|
|
768
|
+
if child_poly is None or tb_info[c_index] is None:
|
|
769
|
+
continue
|
|
770
|
+
for p_index, parent_poly in enumerate(tb_polygons):
|
|
771
|
+
if c_index == p_index: # The child and parent are the same polygon
|
|
772
|
+
continue
|
|
773
|
+
if parent_poly is None or tb_info[p_index] is None:
|
|
774
|
+
continue
|
|
775
|
+
all_points_is_in = True
|
|
776
|
+
for p in child_poly:
|
|
777
|
+
x = int(p[0][0])
|
|
778
|
+
y = int(p[0][1])
|
|
779
|
+
#if cv2.pointPolygonTest(parent_poly, (x, y), True) < -margin:
|
|
780
|
+
if point_in_polygon((int(x), int(y)),parent_poly, True)<-margin:
|
|
781
|
+
# cv2.pointPolygonTest () > 0 means (x,y) is in parent_poly
|
|
782
|
+
all_points_is_in = False
|
|
783
|
+
|
|
784
|
+
if all_points_is_in: # c is in p
|
|
785
|
+
if len(tb_info[c_index]) == 0:
|
|
786
|
+
tb_info[p_index].append([tb_cls_id, c_index])
|
|
787
|
+
tb_info[c_index] = None
|
|
788
|
+
else: # tb[i] has childen
|
|
789
|
+
for child_elm in tb_info[c_index]:
|
|
790
|
+
tb_info[p_index].append(child_elm)
|
|
791
|
+
tb_info[c_index] = None
|
|
792
|
+
break
|
|
793
|
+
|
|
794
|
+
# merge text blocks
|
|
795
|
+
for i in range(len(tb_info)):
|
|
796
|
+
have_only_tb = True
|
|
797
|
+
if tb_info[i] is None:
|
|
798
|
+
continue
|
|
799
|
+
for c_id, _ in tb_info[i]:
|
|
800
|
+
if c_id != tb_cls_id:
|
|
801
|
+
have_only_tb = False
|
|
802
|
+
break
|
|
803
|
+
if have_only_tb:
|
|
804
|
+
tb_info[i] = []
|
|
805
|
+
|
|
806
|
+
return tb_info
|
|
807
|
+
|
|
808
|
+
|
|
809
|
+
def convert_to_xml_string3(img_w, img_h, img_path, classes, result,
|
|
810
|
+
score_thr: float = 0.1,
|
|
811
|
+
min_bbox_size: int = 5,
|
|
812
|
+
use_block_ad: bool = True):
|
|
813
|
+
#import cv2
|
|
814
|
+
|
|
815
|
+
img_name = os.path.basename(img_path)
|
|
816
|
+
s = f'<PAGE IMAGENAME = "{img_name}" WIDTH = "{img_w}" HEIGHT = "{img_h}">\n'
|
|
817
|
+
|
|
818
|
+
res_textblockes = result[0]
|
|
819
|
+
res_bbox = result[1]
|
|
820
|
+
|
|
821
|
+
|
|
822
|
+
# convert text block masks to polygons
|
|
823
|
+
tb_polygons = textblock_to_rect(classes, res_textblockes, min_bbox_size)
|
|
824
|
+
|
|
825
|
+
tb_info, ad_info, table_info, independ_lines = get_relationship_rect(res_bbox, tb_polygons, classes,score_thr=score_thr)
|
|
826
|
+
|
|
827
|
+
# refine text blocks : remove overlapping text blocks
|
|
828
|
+
tb_info = refine_tb_relationship(tb_polygons, tb_info, classes, margin=50)
|
|
829
|
+
#print(tb_info)
|
|
830
|
+
tb_cls_id = classes.index('text_block')
|
|
831
|
+
table_cls_id = classes.index('block_table')
|
|
832
|
+
##Tableの中身
|
|
833
|
+
for i_ba, block_table in enumerate(res_bbox[table_cls_id]):
|
|
834
|
+
#print(ad_info[i_ba], block_ad)
|
|
835
|
+
if table_info[i_ba] is None:
|
|
836
|
+
continue
|
|
837
|
+
#s += ' '
|
|
838
|
+
s = add_block_table_head(s, block_table, block_table[4])
|
|
839
|
+
for c, j in table_info[i_ba]:
|
|
840
|
+
if c == table_cls_id:
|
|
841
|
+
if table_cls_id[j] is None:
|
|
842
|
+
continue
|
|
843
|
+
# add lines in textblock in block_ad
|
|
844
|
+
if len(tb_info[j]) == 0:
|
|
845
|
+
# create and add a line_main elem at least one
|
|
846
|
+
x, y, w, h = make_bbox_from_poly(tb_polygons[j])
|
|
847
|
+
if w >= min_bbox_size and h >= min_bbox_size:
|
|
848
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[0])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" ></LINE>\n'
|
|
849
|
+
else:
|
|
850
|
+
for c_id, i in tb_info[j]:
|
|
851
|
+
line = res_bbox[c_id][i]
|
|
852
|
+
conf = float(line[4])
|
|
853
|
+
|
|
854
|
+
if conf < score_thr:
|
|
855
|
+
continue
|
|
856
|
+
pred_char_cnt=0
|
|
857
|
+
|
|
858
|
+
if len(line)==6:
|
|
859
|
+
pred_char_cnt=float(line[5])
|
|
860
|
+
if c_id == tb_cls_id: # write as Line_main
|
|
861
|
+
x, y, w, h = make_bbox_from_poly(tb_polygons[i])
|
|
862
|
+
if w >= min_bbox_size and h >= min_bbox_size:
|
|
863
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[0])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
864
|
+
else:
|
|
865
|
+
x, y = int(line[0]), int(line[1])
|
|
866
|
+
w, h = int(line[2] - line[0]), int(line[3] - line[1])
|
|
867
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[c_id])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
868
|
+
tb_info[j] = None
|
|
869
|
+
else:
|
|
870
|
+
line = res_bbox[c][j]
|
|
871
|
+
conf = float(line[4])
|
|
872
|
+
if conf < score_thr:
|
|
873
|
+
continue
|
|
874
|
+
pred_char_cnt=0
|
|
875
|
+
if len(line)==6:
|
|
876
|
+
pred_char_cnt=float(line[5])
|
|
877
|
+
x, y = int(line[0]), int(line[1])
|
|
878
|
+
w, h = int(line[2] - line[0]), int(line[3] - line[1])
|
|
879
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[c])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
880
|
+
s += ' </BLOCK>\n'
|
|
881
|
+
##Tableの中身
|
|
882
|
+
if use_block_ad:
|
|
883
|
+
ba_cls_id = classes.index('block_ad')
|
|
884
|
+
for i_ba, block_ad in enumerate(res_bbox[ba_cls_id]):
|
|
885
|
+
#print(ad_info[i_ba], block_ad)
|
|
886
|
+
if ad_info[i_ba] is None:
|
|
887
|
+
continue
|
|
888
|
+
s += ' '
|
|
889
|
+
s = add_block_ad_head(s, block_ad, block_ad[4])
|
|
890
|
+
for c, j in ad_info[i_ba]:
|
|
891
|
+
if c == tb_cls_id:
|
|
892
|
+
if tb_info[j] is None:
|
|
893
|
+
continue
|
|
894
|
+
s = add_text_block_head(s, tb_polygons[j], res_bbox[tb_cls_id][j][4], ' ')
|
|
895
|
+
# add lines in textblock in block_ad
|
|
896
|
+
if len(tb_info[j]) == 0:
|
|
897
|
+
# create and add a line_main elem at least one
|
|
898
|
+
x, y, w, h = make_bbox_from_poly(tb_polygons[j])
|
|
899
|
+
if w >= min_bbox_size and h >= min_bbox_size:
|
|
900
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[0])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}"></LINE>\n'
|
|
901
|
+
else:
|
|
902
|
+
for c_id, i in tb_info[j]:
|
|
903
|
+
line = res_bbox[c_id][i]
|
|
904
|
+
conf = float(line[4])
|
|
905
|
+
if conf < score_thr:
|
|
906
|
+
continue
|
|
907
|
+
pred_char_cnt=0
|
|
908
|
+
if len(line)==6:
|
|
909
|
+
pred_char_cnt=float(line[5])
|
|
910
|
+
if c_id == tb_cls_id: # write as Line_main
|
|
911
|
+
x, y, w, h = make_bbox_from_poly(tb_polygons[i])
|
|
912
|
+
if w >= min_bbox_size and h >= min_bbox_size:
|
|
913
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[0])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
914
|
+
else:
|
|
915
|
+
x, y = int(line[0]), int(line[1])
|
|
916
|
+
w, h = int(line[2] - line[0]), int(line[3] - line[1])
|
|
917
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[c_id])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
918
|
+
s += ' </TEXTBLOCK>\n'
|
|
919
|
+
tb_info[j] = None
|
|
920
|
+
else:
|
|
921
|
+
line = res_bbox[c][j]
|
|
922
|
+
conf = float(line[4])
|
|
923
|
+
if conf < score_thr:
|
|
924
|
+
continue
|
|
925
|
+
pred_char_cnt=0
|
|
926
|
+
if len(line)==6:
|
|
927
|
+
pred_char_cnt=float(line[5])
|
|
928
|
+
x, y = int(line[0]), int(line[1])
|
|
929
|
+
w, h = int(line[2] - line[0]), int(line[3] - line[1])
|
|
930
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[c])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
931
|
+
s += ' </BLOCK>\n'
|
|
932
|
+
# Text block and line elems inside the text block
|
|
933
|
+
for j in range(len(tb_info)):
|
|
934
|
+
|
|
935
|
+
#if tb_info[j] is None or res_bbox[tb_cls_id][j][4] < score_thr or tb_polygons[j] is None: # text block already converted
|
|
936
|
+
if tb_info[j] is None or tb_polygons[j] is None: # text block already converted
|
|
937
|
+
continue
|
|
938
|
+
|
|
939
|
+
if len(tb_info[j]) == 0: # text block without line elms
|
|
940
|
+
# create and add a line_main elem at least one
|
|
941
|
+
x, y, w, h = make_bbox_from_poly(tb_polygons[j])
|
|
942
|
+
s = add_text_block_head(s, tb_polygons[j], res_bbox[tb_cls_id][j][4], ' ')
|
|
943
|
+
if w >= min_bbox_size and h >= min_bbox_size:
|
|
944
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[1])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}"></LINE>\n'
|
|
945
|
+
#continue
|
|
946
|
+
#pass
|
|
947
|
+
else:
|
|
948
|
+
s = add_text_block_head(s, tb_polygons[j], res_bbox[tb_cls_id][j][4], ' ')
|
|
949
|
+
for c_id, i in tb_info[j]:
|
|
950
|
+
line = res_bbox[c_id][i]
|
|
951
|
+
conf = float(line[4])
|
|
952
|
+
if conf < score_thr:
|
|
953
|
+
continue
|
|
954
|
+
pred_char_cnt=0
|
|
955
|
+
if len(line)==6:
|
|
956
|
+
pred_char_cnt=float(line[5])
|
|
957
|
+
if c_id == tb_cls_id: # write as line_main
|
|
958
|
+
x, y, w, h = make_bbox_from_poly(tb_polygons[i])
|
|
959
|
+
if w >= min_bbox_size and h >= min_bbox_size:
|
|
960
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[1])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
961
|
+
else:
|
|
962
|
+
x, y = int(line[0]), int(line[1])
|
|
963
|
+
w, h = int(line[2] - line[0]), int(line[3] - line[1])
|
|
964
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[c_id])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
965
|
+
s += ' </TEXTBLOCK>\n'
|
|
966
|
+
|
|
967
|
+
|
|
968
|
+
# Line elems outside text_block and block_ad
|
|
969
|
+
for c, j in independ_lines:
|
|
970
|
+
line = res_bbox[c][j]
|
|
971
|
+
conf = float(line[4])
|
|
972
|
+
if conf < score_thr:
|
|
973
|
+
continue
|
|
974
|
+
pred_char_cnt=0
|
|
975
|
+
if len(line)==6:
|
|
976
|
+
pred_char_cnt=float(line[5])
|
|
977
|
+
x, y = int(line[0]), int(line[1])
|
|
978
|
+
w, h = int(line[2] - line[0]), int(line[3] - line[1])
|
|
979
|
+
s += f' <LINE TYPE = "{name_to_org_name(classes[c])}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}" PRED_CHAR_CNT="{pred_char_cnt:0.3f}"></LINE>\n'
|
|
980
|
+
|
|
981
|
+
# Block elms other than block_ad
|
|
982
|
+
for c in range(len(classes)):
|
|
983
|
+
cls = classes[c]
|
|
984
|
+
if cls.startswith('block_') and cls!='block_table':
|
|
985
|
+
for block in res_bbox[c]:
|
|
986
|
+
conf = float(block[4])
|
|
987
|
+
if conf < score_thr:
|
|
988
|
+
continue
|
|
989
|
+
x, y = int(block[0]), int(block[1])
|
|
990
|
+
w, h = int(block[2] - block[0]), int(block[3] - block[1])
|
|
991
|
+
s += f' <BLOCK TYPE = "{name_to_org_name(cls)}" X = "{x}" Y = "{y}" WIDTH = "{w}" HEIGHT = "{h}" CONF = "{conf:0.3f}"></BLOCK>\n'
|
|
992
|
+
|
|
993
|
+
s += '</PAGE>\n'
|
|
994
|
+
|
|
995
|
+
return s
|
|
996
|
+
|
|
997
|
+
|
|
998
|
+
def run_layout_detection(img_paths: List[str] = None, list_path: str = None, output_path: str = "layout_prediction.xml",
|
|
999
|
+
config: str = './models/config_file.py',
|
|
1000
|
+
checkpoint: str = 'models/weight_file.pth',
|
|
1001
|
+
device: str = 'cuda:0', score_thr: float = 0.3,
|
|
1002
|
+
use_show: bool = False, dump_dir: str = None,
|
|
1003
|
+
use_time: bool = False):
|
|
1004
|
+
if use_time:
|
|
1005
|
+
import time
|
|
1006
|
+
st_time = time.time()
|
|
1007
|
+
|
|
1008
|
+
if list_path is not None:
|
|
1009
|
+
img_paths = list([s.strip() for s in open(list_path).readlines()])
|
|
1010
|
+
if img_paths is None:
|
|
1011
|
+
print('Please specify --img_paths or --list_path')
|
|
1012
|
+
return -1
|
|
1013
|
+
|
|
1014
|
+
detector = LayoutDetector(config, checkpoint, device)
|
|
1015
|
+
|
|
1016
|
+
if dump_dir is not None:
|
|
1017
|
+
Path(dump_dir).mkdir(exist_ok=True)
|
|
1018
|
+
|
|
1019
|
+
with open(output_path, 'w') as f:
|
|
1020
|
+
def tee(s):
|
|
1021
|
+
print(s, file=f, end="")
|
|
1022
|
+
print(s, file=sys.stdout, end="")
|
|
1023
|
+
|
|
1024
|
+
tee('<?xml version="1.0" encoding="utf-8" standalone="yes"?><OCRDATASET xmlns="">\n')
|
|
1025
|
+
if use_time:
|
|
1026
|
+
head_time = time.time()
|
|
1027
|
+
|
|
1028
|
+
for img_path in tqdm(img_paths):
|
|
1029
|
+
import cv2
|
|
1030
|
+
img = cv2.imread(img_path)
|
|
1031
|
+
|
|
1032
|
+
result = detector.predict(img)
|
|
1033
|
+
|
|
1034
|
+
if use_show:
|
|
1035
|
+
dump_img = detector.show(img, img_path, result, score_thr=score_thr)
|
|
1036
|
+
cv2.namedWindow('show')
|
|
1037
|
+
cv2.imshow('show', dump_img)
|
|
1038
|
+
if 27 == cv2.waitKey(0):
|
|
1039
|
+
break
|
|
1040
|
+
|
|
1041
|
+
if dump_dir is not None:
|
|
1042
|
+
import cv2
|
|
1043
|
+
dump_img = detector.show(img, img_path, result, score_thr=score_thr)
|
|
1044
|
+
cv2.imwrite(str(Path(dump_dir) / Path(img_path).name), dump_img)
|
|
1045
|
+
img_h, img_w = img.shape[0:2]
|
|
1046
|
+
xml_str = convert_to_xml_string2(
|
|
1047
|
+
img_w, img_h, img_path, detector.classes, result, score_thr=score_thr)
|
|
1048
|
+
tee(xml_str)
|
|
1049
|
+
|
|
1050
|
+
tee('</OCRDATASET>\n')
|
|
1051
|
+
# end with
|
|
1052
|
+
if use_time:
|
|
1053
|
+
end_time = time.time()
|
|
1054
|
+
print("+---------------------------------------+")
|
|
1055
|
+
print(f"all elapsed time : {end_time-st_time:0.6f} [sec]")
|
|
1056
|
+
print(f"head time : {head_time-st_time:0.6f} [sec]")
|
|
1057
|
+
infer_time = end_time-head_time
|
|
1058
|
+
infer_per_img = infer_time / len(img_paths)
|
|
1059
|
+
print(f"inference & xmlize time : {infer_time:0.6f} [sec]")
|
|
1060
|
+
print(f" per img : {infer_per_img:0.6f} [sec]")
|
|
1061
|
+
print("+---------------------------------------+")
|
|
1062
|
+
|
|
1063
|
+
"""
|
|
1064
|
+
class InferencerWithCLI:
|
|
1065
|
+
def __init__(self):
|
|
1066
|
+
pass
|
|
1067
|
+
|
|
1068
|
+
def inference_with_cli(self, img, img_path,
|
|
1069
|
+
score_thr: float = 0.3, dump: bool = False):
|
|
1070
|
+
|
|
1071
|
+
node = ET.fromstring(
|
|
1072
|
+
'<?xml version="1.0" standalone="yes"?><OCRDATASET xmlns="">\n</OCRDATASET>\n')
|
|
1073
|
+
|
|
1074
|
+
# prediction
|
|
1075
|
+
if self.detector is None:
|
|
1076
|
+
print('ERROR: Layout detector is not created.')
|
|
1077
|
+
return None
|
|
1078
|
+
result = self.detector.predict(img)
|
|
1079
|
+
|
|
1080
|
+
# xml creation
|
|
1081
|
+
xml_str = convert_to_xml_string_with_data(
|
|
1082
|
+
img.shape[1], img.shape[0], img_path, self.detector.classes, result, score_thr=score_thr)
|
|
1083
|
+
"""
|