-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathextract_words.py
186 lines (133 loc) · 5.49 KB
/
extract_words.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
from abc import abstractmethod
import easyocr
import keras_ocr
import pytesseract
import cv2
import numpy as np
from matplotlib import pyplot as plt
import json
import os
from abc import ABC
"""
There are 2 types of ocr methods.
Retrieves original image and target box coordinates
(id no, first name, last name, date of birth)
and saves txt outputs in json format
"""
CardInfo = {}
class JsonData:
def __init__(self) -> None:
self.text_output = {}
self.data_path = 'test/predictions_json'
self.dict_path = self.data_path + '/data.json'
if not os.path.exists(self.data_path):
os.makedirs(self.data_path)
def saveDict(self, dict_name):
with open(self.dict_path, 'w', encoding='utf-8') as fp:
json.dump(dict_name, fp, ensure_ascii = False)
def loadDict(self):
with open(self.dict_path, 'r', encoding='utf-8') as fp:
data = json.load(fp)
print(data)
class Ocr(ABC):
@abstractmethod
def ocrOutput(self, img_name, img, bbox)->dict:
""" Return text outputs"""
@abstractmethod
def cropRoi(self, img, bbox, denoise)->list:
""" Returns image name list"""
@abstractmethod
def getonlyDigits(inp_str)->str:
""" Return numbers in str format"""
@abstractmethod
def denoiseImage(img):
""" Return opencv image"""
class OcrMethod(Ocr):
def cropRoi(self, img, bbox, denoise):
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
id_infos= ["Tc", "Surname", "Name", "DateofBirth"]
crop_img_names = []
lw_thresh = 3
up_thresh = 3
for info, box in zip(id_infos, bbox):
x, w, y, h = box
crop_img = img_rgb[y-lw_thresh :y+h+up_thresh, x-lw_thresh:x + w + up_thresh]
if denoise:
crop_img = self.denoiseImage(crop_img)
if not os.path.exists("outputs/target_crops/"):
os.makedirs("outputs/target_crops/")
crop_name = "outputs/target_crops/" + str(info) +".jpg"
plt.imsave(crop_name, crop_img)
crop_img_names.append(crop_name)
return crop_img_names
def getonlyDigits(self, inp_str):
num = ""
for c in inp_str:
if c.isdigit():
num = num + c
return num
def denoiseImage(self, img):
img_denoise = cv2.fastNlMeansDenoisingColored(img, None, 10, 10, 7, 15)
imgGray = cv2.cvtColor(img_denoise , cv2.COLOR_BGR2GRAY)
imgBlur = cv2.GaussianBlur(imgGray, (5,5), 1)
ret, imgf = cv2.threshold(imgBlur , 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) #imgf contains Binary image
kernel = np.ones((1,1), np.uint8)
img_dilation = cv2.dilate( imgf, kernel, iterations=1)
img_erosion = cv2.erode(img_dilation , kernel, iterations=1)
return img_erosion
class EasyOcr(OcrMethod):
def __init__(self, border_thresh, denoise,) -> None:
self.reader = easyocr.Reader(['tr','en'])
self.denoise = denoise
self.BORDER_THRSH = border_thresh
def ocrOutput(self, img_name, img, bbox):
"""
it saves the txt outputs as a json format
"""
crop_img_names = self.cropRoi(img, bbox, self.denoise)
id_infos= ["Tc", "Surname", "Name", "DateofBirth"]
jsonData = JsonData()
text_output = {"Tc":"", "Surname":"", "Name":"", "DateofBirth":""}
for info, img in zip(id_infos, crop_img_names):
result = self.reader.readtext(img)
if(len(result)):
box, text, prob = result[0]
text_output[info] = text.upper()
text_output["DateofBirth"] = self.getonlyDigits(text_output["DateofBirth"])
CardInfo[img_name] = text_output
jsonData.saveDict(CardInfo)
return text_output
class TesseractOcr(OcrMethod):
def __init__(self, border_thresh, denoise,) -> None:
self.denoise = denoise
self.BORDER_THRSH = border_thresh
def ocrOutput(self, img_name, img, bbox):
"""
it saves the txt outputs as a json format
"""
crop_img_names = self.cropRoi(img, bbox, self.denoise)
id_infos= ["Tc", "Surname", "Name", "DateofBirth"]
jsonData = JsonData()
text_output = {"Tc":"", "Surname":"", "Name":"", "DateofBirth":""}
for info, img in zip(id_infos, crop_img_names):
text = pytesseract.image_to_string(img)
text_output[info] = text.upper()
text_output["DateofBirth"] = self.getonlyDigits(text_output["DateofBirth"])
CardInfo[img_name] = text_output
jsonData.saveDict(CardInfo)
return text_output
class OcrFactory:
@staticmethod
def select_ocr_method(ocr_method, border_thresh = 3, denoise = False):
if(ocr_method == "EasyOcr"):
return EasyOcr(border_thresh, denoise)
if(ocr_method == "TesseractOcr"):
return TesseractOcr(border_thresh, denoise)
print("Invalid Mehod")
return -1
def ocr_factory(ocr_method = "EasyOcr", border_thresh = 3, denoise = False):
ocr_factory = {
"EasyOcr": EasyOcr,
"TesseractOcr": TesseractOcr
}
return ocr_factory[ocr_method](border_thresh, denoise)