-
Notifications
You must be signed in to change notification settings - Fork 0
/
numberRecognition.py
194 lines (146 loc) · 8.25 KB
/
numberRecognition.py
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
#!/usr/bin/env python
import os
from glob import glob
import tensorflow as tf
from imageio import imread, imsave
from tqdm import tqdm
import ntpath
import numpy as np
import cv2
from dh_segment.io import PAGE
from dh_segment.inference import LoadedModel
from dh_segment.post_processing import boxes_detection, binarization
# To output results in PAGE XML format (http://www.primaresearch.org/schema/PAGE/gts/pagecontent/2013-07-15/)
PAGE_XML_DIR = './page_xml'
def Average(lst):
return sum(lst) / len(lst)
def page_make_binary_mask(probs: np.ndarray, threshold: float = -1) -> np.ndarray:
"""
Computes the binary mask of the detected Page from the probabilities outputed by network
:param probs: array with values in range [0, 1]
:param threshold: threshold between [0 and 1], if negative Otsu's adaptive threshold will be used
:return: binary mask
"""
mask = binarization.thresholding(probs, threshold)
mask = binarization.cleaning_binary(mask, kernel_size=5)
return mask
def format_quad_to_string(quad):
"""
Formats the corner points into a string.
:param quad: coordinates of the quadrilateral
:return:
"""
s = ''
for corner in quad:
s += '{},{},'.format(corner[0], corner[1])
return s[:-1]
if __name__ == '__main__':
# If the model has been trained load the model, otherwise use the given model
model_dir = 'yekta\\yekta\\model_numerals_unet_all_100\\export\\'
if not os.path.exists(model_dir):
model_dir = 'demo/model/'
input_files = glob('NFS_Manisa_Masked\\*')
#input_files = glob('one_image_number_recog/*')
labelPath = 'NFS_Manisa_Masked\\'
output_dir = 'manisa_number_recognized'
os.makedirs(output_dir, exist_ok=True)
# PAGE XML format output
output_pagexml_dir = os.path.join(output_dir, PAGE_XML_DIR)
os.makedirs(output_pagexml_dir, exist_ok=True)
# Store coordinates of page in a .txt file
txt_coordinates = ''
txt_coordinates += "registerID,PageNum,objType,avgW,avgH,isLeft,isEdge,coordW0,coordH0,coordW1,coordH1,coordW2,coordH2,coordW3,coordH3\n"
with tf.Session(): # Start a tensorflow session
# Load the model
m = LoadedModel(model_dir, predict_mode='filename')
for filename in tqdm(input_files, desc='Processed files'):
# For each image, predict each pixel's label
prediction_outputs = m.predict(filename)
probs = prediction_outputs['probs'][0]
original_shape = prediction_outputs['original_shape']
probs = probs[:, :, 1] # Take only class '1' (class 0 is the background, class 1 is the page)
probs = probs / np.max(probs) # Normalize to be in [0, 1]
probs0 = prediction_outputs['probs'][0]
probs0 = probs0[:, :, 0] # Take only class '3' (class 0 is the background, class 1 is the page)
probs0 = probs0 / np.max(probs0) # Normalize to be in [0, 1]
# Binarize the predictions
page_bin0 = page_make_binary_mask(probs0)
page_bin = page_make_binary_mask(probs)
# Upscale to have full resolution image (cv2 uses (w,h) and not (h,w) for giving shapes)
bin_upscaled0 = cv2.resize(page_bin0.astype(np.uint8, copy=False),
tuple(original_shape[::-1]), interpolation=cv2.INTER_NEAREST)
bin_upscaled = cv2.resize(page_bin.astype(np.uint8, copy=False),
tuple(original_shape[::-1]), interpolation=cv2.INTER_NEAREST)
# plt.imshow(bin_upscaled, interpolation='nearest')
# plt.show()
# plt.imshow(bin_upscaled2, interpolation='nearest')
# plt.show()
# plt.imshow(bin_upscaled3, interpolation='nearest')
# plt.show()
pred_page_coords0 = boxes_detection.find_boxes(bin_upscaled0.astype(np.uint8, copy=False),
mode='min_rectangle')
# Find quadrilateral enclosing the page
pred_page_coords = boxes_detection.find_boxes(bin_upscaled.astype(np.uint8, copy=False),
mode='min_rectangle')
# Draw page box on original image and export it. Add also box coordinates to the txt file
original_img = imread(filename, pilmode='RGB')
if pred_page_coords is not None:
for x in range(0, len(pred_page_coords0)):
pred_page_coords_element0 = pred_page_coords0[x]
# cv2.polylines(original_img, [pred_page_coords_element0[:, None, :]], True, (0, 0, 0), thickness=10)
# Write corners points into a .txt file
filename_w_o_ext = os.path.splitext(filename)[0]
filename = ntpath.basename(filename_w_o_ext)
data = filename.split("_")
registerID = data[4]
pageNum = data[5]
isLeft = 0
isEdge = 0
previousAverage = [0, 0]
weight = bin_upscaled.shape[1] / 2
for x in range(0, len(pred_page_coords)):
pred_page_coords_element2 = pred_page_coords[x]
type2Coord = pred_page_coords[x]
typeCoord2_w = pred_page_coords[x][0]
typeCoord2_h = pred_page_coords[x][1]
typeCoord2_h1 = pred_page_coords[x][2]
typeCoord2_h2 = pred_page_coords[x][3]
max_w2 = max(typeCoord2_w[0], typeCoord2_h[0], typeCoord2_h1[0], typeCoord2_h2[0])
max_h2 = max(typeCoord2_w[1], typeCoord2_h[1], typeCoord2_h1[1], typeCoord2_h2[1])
min_w2 = min(typeCoord2_w[0], typeCoord2_h[0], typeCoord2_h1[0], typeCoord2_h2[0])
min_h2 = min(typeCoord2_w[1], typeCoord2_h[1], typeCoord2_h1[1], typeCoord2_h2[1])
Area = (max_h2 - min_h2) * (max_w2 - min_w2)
average2 = Average(type2Coord)
isLeft = 0
isEdge = 0
if (average2[0] < weight):
isLeft = 1
for y in range (0, len(pred_page_coords[x])):
if (pred_page_coords[x][y][0] > 2290 * 0.98 or pred_page_coords[x][y][1] > 2990 * 0.98 or pred_page_coords[x][y][0] < 50 or pred_page_coords[x][y][1] < 50):
isEdge = 1
if (isEdge == 0):
pred_page_coords_element = pred_page_coords[x]
page_border = PAGE.Border(
coords=PAGE.Point.cv2_to_point_list(pred_page_coords_element2[:, None, :]))
cv2.polylines(original_img, [pred_page_coords_element[:, None, :]], True, (0, 255, 0),
thickness=5)
txt_coordinates += '{},{}\n'.format(
registerID + "," + pageNum + ",2," + str(int(average2[0])) + "," + str(
int(average2[1])) + "," + str(isLeft) + "," + str(isEdge),
format_quad_to_string(pred_page_coords[x]))
# for x in range(0, len(pred_page_coords0)):
# txt_coordinates += '{};{}\n'.format(filename + ",0,", format_quad_to_string(pred_page_coords0[x]))
# Create page region and XML file
for x in range(0, len(pred_page_coords0)):
pred_page_coords_element0 = pred_page_coords0[x]
page_border = PAGE.Border(
coords=PAGE.Point.cv2_to_point_list(pred_page_coords_element0[:, None, :]))
basename = os.path.basename(filename).split('.')[0]
imsave(os.path.join(output_dir, '{}_boxes.jpg'.format(basename)), original_img)
page_xml = PAGE.Page(image_filename=filename, image_width=original_shape[1], image_height=original_shape[0],
page_border=page_border)
xml_filename = os.path.join(output_pagexml_dir, '{}.xml'.format(basename))
page_xml.write_to_file(xml_filename, creator_name='PageExtractor')
# Save txt file
with open(os.path.join(output_dir, 'recognized_numbers.csv'), 'w') as f:
f.write(txt_coordinates)