Spaces:
Sleeping
Sleeping
ardakshalkar
commited on
Commit
•
e4d7281
1
Parent(s):
0c6c9e6
first commit
Browse files- KZReader.py +108 -0
- app.py +36 -0
- models/__pycache__/best_norm_ED.cpython-311.pyc +0 -0
- models/best_norm_ED.pth +3 -0
- models/best_norm_ED.py +538 -0
- models/best_norm_ED.yaml +52 -0
- models/craft_mlt_25k.pth +3 -0
KZReader.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image, ImageDraw, ImageFont
|
5 |
+
from tqdm import tqdm
|
6 |
+
import os
|
7 |
+
|
8 |
+
import easyocr
|
9 |
+
|
10 |
+
models_dir = "./models"
|
11 |
+
images_dir = "./images"
|
12 |
+
output_dir = "./output"
|
13 |
+
dirs = [models_dir, images_dir, output_dir]
|
14 |
+
for d in dirs:
|
15 |
+
if not os.path.exists(output_dir):
|
16 |
+
os.makedirs(output_dir)
|
17 |
+
|
18 |
+
|
19 |
+
class KZReader:
|
20 |
+
def __init__(self):
|
21 |
+
self.reader = easyocr.Reader(
|
22 |
+
['en'],
|
23 |
+
gpu=True,
|
24 |
+
recog_network='best_norm_ED',
|
25 |
+
detect_network="craft",
|
26 |
+
user_network_directory=models_dir,
|
27 |
+
model_storage_directory=models_dir,
|
28 |
+
) # this needs to run only once to load the model into memory
|
29 |
+
def readtext(self, image,paragraph):
|
30 |
+
|
31 |
+
result = reader.readtext(image = image, paragraph=True)
|
32 |
+
return result
|
33 |
+
|
34 |
+
"""
|
35 |
+
Upload easy OCR model files with the same name and font file named Ubuntu-Regular.ttf, examples:
|
36 |
+
best_norm_ED.pth
|
37 |
+
best_norm_ED.py
|
38 |
+
best_norm_ED.yaml
|
39 |
+
Ubuntu-Regular.ttf
|
40 |
+
|
41 |
+
to models directory
|
42 |
+
|
43 |
+
Upload image files you want to test, examples:
|
44 |
+
kz_book_simple.jpeg
|
45 |
+
kz_blur.jpg
|
46 |
+
kz_book_complex.jpg
|
47 |
+
|
48 |
+
to images directory
|
49 |
+
"""
|
50 |
+
|
51 |
+
'''
|
52 |
+
font_path = models_dir + "/Ubuntu-Regular.ttf"
|
53 |
+
|
54 |
+
reader = easyocr.Reader(
|
55 |
+
['en'],
|
56 |
+
gpu=True,
|
57 |
+
recog_network='best_norm_ED',
|
58 |
+
detect_network="craft",
|
59 |
+
user_network_directory=models_dir,
|
60 |
+
model_storage_directory=models_dir,
|
61 |
+
) # this needs to run only once to load the model into memory
|
62 |
+
|
63 |
+
image_extensions = (".jpg", ".jpeg", ".png")
|
64 |
+
'''
|
65 |
+
|
66 |
+
'''
|
67 |
+
for image_name in tqdm(os.listdir(images_dir)):
|
68 |
+
if not image_name.lower().endswith(image_extensions):
|
69 |
+
print(f'unsupported file {image_name}')
|
70 |
+
continue
|
71 |
+
image_path = f'{images_dir}/{image_name}'
|
72 |
+
print(image_path)
|
73 |
+
# Read image as numpy array
|
74 |
+
image = cv2.imread(image_path)
|
75 |
+
|
76 |
+
# Rotate the image by 270 degrees
|
77 |
+
# image = cv2.rotate(image, cv2.ROTATE_90_CLOCKWISE)
|
78 |
+
|
79 |
+
# Convert the image from BGR to RGB (because OpenCV loads images in BGR format)
|
80 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
81 |
+
results = reader.readtext(image=image)
|
82 |
+
|
83 |
+
# Load custom font
|
84 |
+
font = ImageFont.truetype(font_path, 32)
|
85 |
+
|
86 |
+
# Display the results
|
87 |
+
for (bbox, text, prob) in results:
|
88 |
+
# Get the bounding box coordinates
|
89 |
+
(top_left, top_right, bottom_right, bottom_left) = bbox
|
90 |
+
top_left = (int(top_left[0]), int(top_left[1]))
|
91 |
+
bottom_right = (int(bottom_right[0]), int(bottom_right[1]))
|
92 |
+
|
93 |
+
# Draw the bounding box on the image
|
94 |
+
cv2.rectangle(image, top_left, bottom_right, (0, 255, 0), 2)
|
95 |
+
|
96 |
+
# Convert the OpenCV image to a PIL image, draw the text, then convert back to an OpenCV image
|
97 |
+
image_pil = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
|
98 |
+
draw = ImageDraw.Draw(image_pil)
|
99 |
+
draw.text((top_left[0], top_left[1] - 40), text, font=font, fill=(0, 0, 255))
|
100 |
+
image = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
|
101 |
+
|
102 |
+
# Save image
|
103 |
+
cv2.imwrite( f'{output_dir}/{image_name}', image)
|
104 |
+
|
105 |
+
# reader.readtext(image = image, paragraph=True)
|
106 |
+
|
107 |
+
|
108 |
+
'''
|
app.py
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import numpy as np
|
3 |
+
import streamlit as st
|
4 |
+
import easyocr
|
5 |
+
import PIL
|
6 |
+
from PIL import Image, ImageDraw
|
7 |
+
from matplotlib import pyplot as plt
|
8 |
+
from KZReader import KZReader
|
9 |
+
|
10 |
+
|
11 |
+
# main title
|
12 |
+
st.set_page_config(layout="wide")
|
13 |
+
st.title("Get text from image with EasyOCR")
|
14 |
+
# subtitle
|
15 |
+
st.markdown("## EasyOCRR with Streamlit")
|
16 |
+
col1, col2 = st.columns(2)
|
17 |
+
uploaded_file = col1.file_uploader("Upload your file here ",type=['png','jpeg','jpg','pdf'])
|
18 |
+
if uploaded_file is not None:
|
19 |
+
col1.image(uploaded_file) #display
|
20 |
+
#print("GOGO ",type(uploaded_file))
|
21 |
+
|
22 |
+
image_extensions = (".jpg", ".jpeg", ".png")
|
23 |
+
pdf_extensions = (".pdf")
|
24 |
+
if uploaded_file.name.lower().endswith(image_extensions):
|
25 |
+
image = Image.open(uploaded_file)
|
26 |
+
reader = KZReader() #easyocr.Reader(['tr','en'], gpu=False)
|
27 |
+
result = reader.readtext(np.array(image),paragraph=True) # turn image to numpy array
|
28 |
+
#print(len(result))
|
29 |
+
result_text = "\n\n".join([item[1] for item in result])
|
30 |
+
col2.markdown(result_text)
|
31 |
+
elif uploaded_file.name.lower().endswith(pdf_extensions):
|
32 |
+
print("PDF file")
|
33 |
+
col2.markdown("PDF file")
|
34 |
+
else:
|
35 |
+
print(f'unsupported file {image_name}')
|
36 |
+
col2.markdown("ERROR")
|
models/__pycache__/best_norm_ED.cpython-311.pyc
ADDED
Binary file (40.8 kB). View file
|
|
models/best_norm_ED.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:927d3bf23c46f9e190819bcc244fd9ba02d8c93aaff28a2c07683130abfd9238
|
3 |
+
size 15163627
|
models/best_norm_ED.py
ADDED
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
7 |
+
|
8 |
+
|
9 |
+
class TPS_SpatialTransformerNetwork(nn.Module):
|
10 |
+
""" Rectification Network of RARE, namely TPS based STN """
|
11 |
+
|
12 |
+
def __init__(self, F, I_size, I_r_size, I_channel_num=1):
|
13 |
+
""" Based on RARE TPS
|
14 |
+
input:
|
15 |
+
batch_I: Batch Input Image [batch_size x I_channel_num x I_height x I_width]
|
16 |
+
I_size : (height, width) of the input image I
|
17 |
+
I_r_size : (height, width) of the rectified image I_r
|
18 |
+
I_channel_num : the number of channels of the input image I
|
19 |
+
output:
|
20 |
+
batch_I_r: rectified image [batch_size x I_channel_num x I_r_height x I_r_width]
|
21 |
+
"""
|
22 |
+
super(TPS_SpatialTransformerNetwork, self).__init__()
|
23 |
+
self.F = F
|
24 |
+
self.I_size = I_size
|
25 |
+
self.I_r_size = I_r_size # = (I_r_height, I_r_width)
|
26 |
+
self.I_channel_num = I_channel_num
|
27 |
+
self.LocalizationNetwork = LocalizationNetwork(self.F, self.I_channel_num)
|
28 |
+
self.GridGenerator = GridGenerator(self.F, self.I_r_size)
|
29 |
+
|
30 |
+
def forward(self, batch_I):
|
31 |
+
batch_C_prime = self.LocalizationNetwork(batch_I) # batch_size x K x 2
|
32 |
+
build_P_prime = self.GridGenerator.build_P_prime(batch_C_prime) # batch_size x n (= I_r_width x I_r_height) x 2
|
33 |
+
build_P_prime_reshape = build_P_prime.reshape([build_P_prime.size(0), self.I_r_size[0], self.I_r_size[1], 2])
|
34 |
+
batch_I_r = F.grid_sample(batch_I, build_P_prime_reshape, padding_mode='border')
|
35 |
+
|
36 |
+
return batch_I_r
|
37 |
+
|
38 |
+
|
39 |
+
class LocalizationNetwork(nn.Module):
|
40 |
+
""" Localization Network of RARE, which predicts C' (K x 2) from I (I_width x I_height) """
|
41 |
+
|
42 |
+
def __init__(self, F, I_channel_num):
|
43 |
+
super(LocalizationNetwork, self).__init__()
|
44 |
+
self.F = F
|
45 |
+
self.I_channel_num = I_channel_num
|
46 |
+
self.conv = nn.Sequential(
|
47 |
+
nn.Conv2d(in_channels=self.I_channel_num, out_channels=64, kernel_size=3, stride=1, padding=1,
|
48 |
+
bias=False), nn.BatchNorm2d(64), nn.ReLU(True),
|
49 |
+
nn.MaxPool2d(2, 2), # batch_size x 64 x I_height/2 x I_width/2
|
50 |
+
nn.Conv2d(64, 128, 3, 1, 1, bias=False), nn.BatchNorm2d(128), nn.ReLU(True),
|
51 |
+
nn.MaxPool2d(2, 2), # batch_size x 128 x I_height/4 x I_width/4
|
52 |
+
nn.Conv2d(128, 256, 3, 1, 1, bias=False), nn.BatchNorm2d(256), nn.ReLU(True),
|
53 |
+
nn.MaxPool2d(2, 2), # batch_size x 256 x I_height/8 x I_width/8
|
54 |
+
nn.Conv2d(256, 512, 3, 1, 1, bias=False), nn.BatchNorm2d(512), nn.ReLU(True),
|
55 |
+
nn.AdaptiveAvgPool2d(1) # batch_size x 512
|
56 |
+
)
|
57 |
+
|
58 |
+
self.localization_fc1 = nn.Sequential(nn.Linear(512, 256), nn.ReLU(True))
|
59 |
+
self.localization_fc2 = nn.Linear(256, self.F * 2)
|
60 |
+
|
61 |
+
# Init fc2 in LocalizationNetwork
|
62 |
+
self.localization_fc2.weight.data.fill_(0)
|
63 |
+
""" see RARE paper Fig. 6 (a) """
|
64 |
+
ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
|
65 |
+
ctrl_pts_y_top = np.linspace(0.0, -1.0, num=int(F / 2))
|
66 |
+
ctrl_pts_y_bottom = np.linspace(1.0, 0.0, num=int(F / 2))
|
67 |
+
ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
|
68 |
+
ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
|
69 |
+
initial_bias = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
|
70 |
+
self.localization_fc2.bias.data = torch.from_numpy(initial_bias).float().view(-1)
|
71 |
+
|
72 |
+
def forward(self, batch_I):
|
73 |
+
"""
|
74 |
+
input: batch_I : Batch Input Image [batch_size x I_channel_num x I_height x I_width]
|
75 |
+
output: batch_C_prime : Predicted coordinates of fiducial points for input batch [batch_size x F x 2]
|
76 |
+
"""
|
77 |
+
batch_size = batch_I.size(0)
|
78 |
+
features = self.conv(batch_I).view(batch_size, -1)
|
79 |
+
batch_C_prime = self.localization_fc2(self.localization_fc1(features)).view(batch_size, self.F, 2)
|
80 |
+
return batch_C_prime
|
81 |
+
|
82 |
+
|
83 |
+
class GridGenerator(nn.Module):
|
84 |
+
""" Grid Generator of RARE, which produces P_prime by multiplying T with P """
|
85 |
+
|
86 |
+
def __init__(self, F, I_r_size):
|
87 |
+
""" Generate P_hat and inv_delta_C for later """
|
88 |
+
super(GridGenerator, self).__init__()
|
89 |
+
self.eps = 1e-6
|
90 |
+
self.I_r_height, self.I_r_width = I_r_size
|
91 |
+
self.F = F
|
92 |
+
self.C = self._build_C(self.F) # F x 2
|
93 |
+
self.P = self._build_P(self.I_r_width, self.I_r_height)
|
94 |
+
## for multi-gpu, you need register buffer
|
95 |
+
self.register_buffer("inv_delta_C", torch.tensor(self._build_inv_delta_C(self.F, self.C)).float()) # F+3 x F+3
|
96 |
+
self.register_buffer("P_hat", torch.tensor(self._build_P_hat(self.F, self.C, self.P)).float()) # n x F+3
|
97 |
+
## for fine-tuning with different image width, you may use below instead of self.register_buffer
|
98 |
+
# self.inv_delta_C = torch.tensor(self._build_inv_delta_C(self.F, self.C)).float().cuda() # F+3 x F+3
|
99 |
+
# self.P_hat = torch.tensor(self._build_P_hat(self.F, self.C, self.P)).float().cuda() # n x F+3
|
100 |
+
|
101 |
+
def _build_C(self, F):
|
102 |
+
""" Return coordinates of fiducial points in I_r; C """
|
103 |
+
ctrl_pts_x = np.linspace(-1.0, 1.0, int(F / 2))
|
104 |
+
ctrl_pts_y_top = -1 * np.ones(int(F / 2))
|
105 |
+
ctrl_pts_y_bottom = np.ones(int(F / 2))
|
106 |
+
ctrl_pts_top = np.stack([ctrl_pts_x, ctrl_pts_y_top], axis=1)
|
107 |
+
ctrl_pts_bottom = np.stack([ctrl_pts_x, ctrl_pts_y_bottom], axis=1)
|
108 |
+
C = np.concatenate([ctrl_pts_top, ctrl_pts_bottom], axis=0)
|
109 |
+
return C # F x 2
|
110 |
+
|
111 |
+
def _build_inv_delta_C(self, F, C):
|
112 |
+
""" Return inv_delta_C which is needed to calculate T """
|
113 |
+
hat_C = np.zeros((F, F), dtype=float) # F x F
|
114 |
+
for i in range(0, F):
|
115 |
+
for j in range(i, F):
|
116 |
+
r = np.linalg.norm(C[i] - C[j])
|
117 |
+
hat_C[i, j] = r
|
118 |
+
hat_C[j, i] = r
|
119 |
+
np.fill_diagonal(hat_C, 1)
|
120 |
+
hat_C = (hat_C ** 2) * np.log(hat_C)
|
121 |
+
# print(C.shape, hat_C.shape)
|
122 |
+
delta_C = np.concatenate( # F+3 x F+3
|
123 |
+
[
|
124 |
+
np.concatenate([np.ones((F, 1)), C, hat_C], axis=1), # F x F+3
|
125 |
+
np.concatenate([np.zeros((2, 3)), np.transpose(C)], axis=1), # 2 x F+3
|
126 |
+
np.concatenate([np.zeros((1, 3)), np.ones((1, F))], axis=1) # 1 x F+3
|
127 |
+
],
|
128 |
+
axis=0
|
129 |
+
)
|
130 |
+
inv_delta_C = np.linalg.inv(delta_C)
|
131 |
+
return inv_delta_C # F+3 x F+3
|
132 |
+
|
133 |
+
def _build_P(self, I_r_width, I_r_height):
|
134 |
+
I_r_grid_x = (np.arange(-I_r_width, I_r_width, 2) + 1.0) / I_r_width # self.I_r_width
|
135 |
+
I_r_grid_y = (np.arange(-I_r_height, I_r_height, 2) + 1.0) / I_r_height # self.I_r_height
|
136 |
+
P = np.stack( # self.I_r_width x self.I_r_height x 2
|
137 |
+
np.meshgrid(I_r_grid_x, I_r_grid_y),
|
138 |
+
axis=2
|
139 |
+
)
|
140 |
+
return P.reshape([-1, 2]) # n (= self.I_r_width x self.I_r_height) x 2
|
141 |
+
|
142 |
+
def _build_P_hat(self, F, C, P):
|
143 |
+
n = P.shape[0] # n (= self.I_r_width x self.I_r_height)
|
144 |
+
P_tile = np.tile(np.expand_dims(P, axis=1), (1, F, 1)) # n x 2 -> n x 1 x 2 -> n x F x 2
|
145 |
+
C_tile = np.expand_dims(C, axis=0) # 1 x F x 2
|
146 |
+
P_diff = P_tile - C_tile # n x F x 2
|
147 |
+
rbf_norm = np.linalg.norm(P_diff, ord=2, axis=2, keepdims=False) # n x F
|
148 |
+
rbf = np.multiply(np.square(rbf_norm), np.log(rbf_norm + self.eps)) # n x F
|
149 |
+
P_hat = np.concatenate([np.ones((n, 1)), P, rbf], axis=1)
|
150 |
+
return P_hat # n x F+3
|
151 |
+
|
152 |
+
def build_P_prime(self, batch_C_prime):
|
153 |
+
""" Generate Grid from batch_C_prime [batch_size x F x 2] """
|
154 |
+
batch_size = batch_C_prime.size(0)
|
155 |
+
batch_inv_delta_C = self.inv_delta_C.repeat(batch_size, 1, 1)
|
156 |
+
batch_P_hat = self.P_hat.repeat(batch_size, 1, 1)
|
157 |
+
batch_C_prime_with_zeros = torch.cat((batch_C_prime, torch.zeros(
|
158 |
+
batch_size, 3, 2).float().to(device)), dim=1) # batch_size x F+3 x 2
|
159 |
+
batch_T = torch.bmm(batch_inv_delta_C, batch_C_prime_with_zeros) # batch_size x F+3 x 2
|
160 |
+
batch_P_prime = torch.bmm(batch_P_hat, batch_T) # batch_size x n x 2
|
161 |
+
return batch_P_prime # batch_size x n x 2
|
162 |
+
|
163 |
+
|
164 |
+
class VGG_FeatureExtractor(nn.Module):
|
165 |
+
""" FeatureExtractor of CRNN (https://arxiv.org/pdf/1507.05717.pdf) """
|
166 |
+
|
167 |
+
def __init__(self, input_channel, output_channel=512):
|
168 |
+
super(VGG_FeatureExtractor, self).__init__()
|
169 |
+
self.output_channel = [int(output_channel / 8), int(output_channel / 4),
|
170 |
+
int(output_channel / 2), output_channel] # [64, 128, 256, 512]
|
171 |
+
self.ConvNet = nn.Sequential(
|
172 |
+
nn.Conv2d(input_channel, self.output_channel[0], 3, 1, 1), nn.ReLU(True),
|
173 |
+
nn.MaxPool2d(2, 2), # 64x16x50
|
174 |
+
nn.Conv2d(self.output_channel[0], self.output_channel[1], 3, 1, 1), nn.ReLU(True),
|
175 |
+
nn.MaxPool2d(2, 2), # 128x8x25
|
176 |
+
nn.Conv2d(self.output_channel[1], self.output_channel[2], 3, 1, 1), nn.ReLU(True), # 256x8x25
|
177 |
+
nn.Conv2d(self.output_channel[2], self.output_channel[2], 3, 1, 1), nn.ReLU(True),
|
178 |
+
nn.MaxPool2d((2, 1), (2, 1)), # 256x4x25
|
179 |
+
nn.Conv2d(self.output_channel[2], self.output_channel[3], 3, 1, 1, bias=False),
|
180 |
+
nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True), # 512x4x25
|
181 |
+
nn.Conv2d(self.output_channel[3], self.output_channel[3], 3, 1, 1, bias=False),
|
182 |
+
nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True),
|
183 |
+
nn.MaxPool2d((2, 1), (2, 1)), # 512x2x25
|
184 |
+
nn.Conv2d(self.output_channel[3], self.output_channel[3], 2, 1, 0), nn.ReLU(True)) # 512x1x24
|
185 |
+
|
186 |
+
def forward(self, input):
|
187 |
+
return self.ConvNet(input)
|
188 |
+
|
189 |
+
|
190 |
+
class RCNN_FeatureExtractor(nn.Module):
|
191 |
+
""" FeatureExtractor of GRCNN (https://papers.nips.cc/paper/6637-gated-recurrent-convolution-neural-network-for-ocr.pdf) """
|
192 |
+
|
193 |
+
def __init__(self, input_channel, output_channel=512):
|
194 |
+
super(RCNN_FeatureExtractor, self).__init__()
|
195 |
+
self.output_channel = [int(output_channel / 8), int(output_channel / 4),
|
196 |
+
int(output_channel / 2), output_channel] # [64, 128, 256, 512]
|
197 |
+
self.ConvNet = nn.Sequential(
|
198 |
+
nn.Conv2d(input_channel, self.output_channel[0], 3, 1, 1), nn.ReLU(True),
|
199 |
+
nn.MaxPool2d(2, 2), # 64 x 16 x 50
|
200 |
+
GRCL(self.output_channel[0], self.output_channel[0], num_iteration=5, kernel_size=3, pad=1),
|
201 |
+
nn.MaxPool2d(2, 2), # 64 x 8 x 25
|
202 |
+
GRCL(self.output_channel[0], self.output_channel[1], num_iteration=5, kernel_size=3, pad=1),
|
203 |
+
nn.MaxPool2d(2, (2, 1), (0, 1)), # 128 x 4 x 26
|
204 |
+
GRCL(self.output_channel[1], self.output_channel[2], num_iteration=5, kernel_size=3, pad=1),
|
205 |
+
nn.MaxPool2d(2, (2, 1), (0, 1)), # 256 x 2 x 27
|
206 |
+
nn.Conv2d(self.output_channel[2], self.output_channel[3], 2, 1, 0, bias=False),
|
207 |
+
nn.BatchNorm2d(self.output_channel[3]), nn.ReLU(True)) # 512 x 1 x 26
|
208 |
+
|
209 |
+
def forward(self, input):
|
210 |
+
return self.ConvNet(input)
|
211 |
+
|
212 |
+
|
213 |
+
class ResNet_FeatureExtractor(nn.Module):
|
214 |
+
""" FeatureExtractor of FAN (http://openaccess.thecvf.com/content_ICCV_2017/papers/Cheng_Focusing_Attention_Towards_ICCV_2017_paper.pdf) """
|
215 |
+
|
216 |
+
def __init__(self, input_channel, output_channel=512):
|
217 |
+
super(ResNet_FeatureExtractor, self).__init__()
|
218 |
+
self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [1, 2, 5, 3])
|
219 |
+
|
220 |
+
def forward(self, input):
|
221 |
+
return self.ConvNet(input)
|
222 |
+
|
223 |
+
|
224 |
+
# For Gated RCNN
|
225 |
+
class GRCL(nn.Module):
|
226 |
+
|
227 |
+
def __init__(self, input_channel, output_channel, num_iteration, kernel_size, pad):
|
228 |
+
super(GRCL, self).__init__()
|
229 |
+
self.wgf_u = nn.Conv2d(input_channel, output_channel, 1, 1, 0, bias=False)
|
230 |
+
self.wgr_x = nn.Conv2d(output_channel, output_channel, 1, 1, 0, bias=False)
|
231 |
+
self.wf_u = nn.Conv2d(input_channel, output_channel, kernel_size, 1, pad, bias=False)
|
232 |
+
self.wr_x = nn.Conv2d(output_channel, output_channel, kernel_size, 1, pad, bias=False)
|
233 |
+
|
234 |
+
self.BN_x_init = nn.BatchNorm2d(output_channel)
|
235 |
+
|
236 |
+
self.num_iteration = num_iteration
|
237 |
+
self.GRCL = [GRCL_unit(output_channel) for _ in range(num_iteration)]
|
238 |
+
self.GRCL = nn.Sequential(*self.GRCL)
|
239 |
+
|
240 |
+
def forward(self, input):
|
241 |
+
""" The input of GRCL is consistant over time t, which is denoted by u(0)
|
242 |
+
thus wgf_u / wf_u is also consistant over time t.
|
243 |
+
"""
|
244 |
+
wgf_u = self.wgf_u(input)
|
245 |
+
wf_u = self.wf_u(input)
|
246 |
+
x = F.relu(self.BN_x_init(wf_u))
|
247 |
+
|
248 |
+
for i in range(self.num_iteration):
|
249 |
+
x = self.GRCL[i](wgf_u, self.wgr_x(x), wf_u, self.wr_x(x))
|
250 |
+
|
251 |
+
return x
|
252 |
+
|
253 |
+
|
254 |
+
class GRCL_unit(nn.Module):
|
255 |
+
|
256 |
+
def __init__(self, output_channel):
|
257 |
+
super(GRCL_unit, self).__init__()
|
258 |
+
self.BN_gfu = nn.BatchNorm2d(output_channel)
|
259 |
+
self.BN_grx = nn.BatchNorm2d(output_channel)
|
260 |
+
self.BN_fu = nn.BatchNorm2d(output_channel)
|
261 |
+
self.BN_rx = nn.BatchNorm2d(output_channel)
|
262 |
+
self.BN_Gx = nn.BatchNorm2d(output_channel)
|
263 |
+
|
264 |
+
def forward(self, wgf_u, wgr_x, wf_u, wr_x):
|
265 |
+
G_first_term = self.BN_gfu(wgf_u)
|
266 |
+
G_second_term = self.BN_grx(wgr_x)
|
267 |
+
G = F.sigmoid(G_first_term + G_second_term)
|
268 |
+
|
269 |
+
x_first_term = self.BN_fu(wf_u)
|
270 |
+
x_second_term = self.BN_Gx(self.BN_rx(wr_x) * G)
|
271 |
+
x = F.relu(x_first_term + x_second_term)
|
272 |
+
|
273 |
+
return x
|
274 |
+
|
275 |
+
|
276 |
+
class BasicBlock(nn.Module):
|
277 |
+
expansion = 1
|
278 |
+
|
279 |
+
def __init__(self, inplanes, planes, stride=1, downsample=None):
|
280 |
+
super(BasicBlock, self).__init__()
|
281 |
+
self.conv1 = self._conv3x3(inplanes, planes)
|
282 |
+
self.bn1 = nn.BatchNorm2d(planes)
|
283 |
+
self.conv2 = self._conv3x3(planes, planes)
|
284 |
+
self.bn2 = nn.BatchNorm2d(planes)
|
285 |
+
self.relu = nn.ReLU(inplace=True)
|
286 |
+
self.downsample = downsample
|
287 |
+
self.stride = stride
|
288 |
+
|
289 |
+
def _conv3x3(self, in_planes, out_planes, stride=1):
|
290 |
+
"3x3 convolution with padding"
|
291 |
+
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
|
292 |
+
padding=1, bias=False)
|
293 |
+
|
294 |
+
def forward(self, x):
|
295 |
+
residual = x
|
296 |
+
|
297 |
+
out = self.conv1(x)
|
298 |
+
out = self.bn1(out)
|
299 |
+
out = self.relu(out)
|
300 |
+
|
301 |
+
out = self.conv2(out)
|
302 |
+
out = self.bn2(out)
|
303 |
+
|
304 |
+
if self.downsample is not None:
|
305 |
+
residual = self.downsample(x)
|
306 |
+
out += residual
|
307 |
+
out = self.relu(out)
|
308 |
+
|
309 |
+
return out
|
310 |
+
|
311 |
+
|
312 |
+
class ResNet(nn.Module):
|
313 |
+
|
314 |
+
def __init__(self, input_channel, output_channel, block, layers):
|
315 |
+
super(ResNet, self).__init__()
|
316 |
+
|
317 |
+
self.output_channel_block = [int(output_channel / 4), int(output_channel / 2), output_channel, output_channel]
|
318 |
+
|
319 |
+
self.inplanes = int(output_channel / 8)
|
320 |
+
self.conv0_1 = nn.Conv2d(input_channel, int(output_channel / 16),
|
321 |
+
kernel_size=3, stride=1, padding=1, bias=False)
|
322 |
+
self.bn0_1 = nn.BatchNorm2d(int(output_channel / 16))
|
323 |
+
self.conv0_2 = nn.Conv2d(int(output_channel / 16), self.inplanes,
|
324 |
+
kernel_size=3, stride=1, padding=1, bias=False)
|
325 |
+
self.bn0_2 = nn.BatchNorm2d(self.inplanes)
|
326 |
+
self.relu = nn.ReLU(inplace=True)
|
327 |
+
|
328 |
+
self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
|
329 |
+
self.layer1 = self._make_layer(block, self.output_channel_block[0], layers[0])
|
330 |
+
self.conv1 = nn.Conv2d(self.output_channel_block[0], self.output_channel_block[
|
331 |
+
0], kernel_size=3, stride=1, padding=1, bias=False)
|
332 |
+
self.bn1 = nn.BatchNorm2d(self.output_channel_block[0])
|
333 |
+
|
334 |
+
self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
|
335 |
+
self.layer2 = self._make_layer(block, self.output_channel_block[1], layers[1], stride=1)
|
336 |
+
self.conv2 = nn.Conv2d(self.output_channel_block[1], self.output_channel_block[
|
337 |
+
1], kernel_size=3, stride=1, padding=1, bias=False)
|
338 |
+
self.bn2 = nn.BatchNorm2d(self.output_channel_block[1])
|
339 |
+
|
340 |
+
self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=(2, 1), padding=(0, 1))
|
341 |
+
self.layer3 = self._make_layer(block, self.output_channel_block[2], layers[2], stride=1)
|
342 |
+
self.conv3 = nn.Conv2d(self.output_channel_block[2], self.output_channel_block[
|
343 |
+
2], kernel_size=3, stride=1, padding=1, bias=False)
|
344 |
+
self.bn3 = nn.BatchNorm2d(self.output_channel_block[2])
|
345 |
+
|
346 |
+
self.layer4 = self._make_layer(block, self.output_channel_block[3], layers[3], stride=1)
|
347 |
+
self.conv4_1 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[
|
348 |
+
3], kernel_size=2, stride=(2, 1), padding=(0, 1), bias=False)
|
349 |
+
self.bn4_1 = nn.BatchNorm2d(self.output_channel_block[3])
|
350 |
+
self.conv4_2 = nn.Conv2d(self.output_channel_block[3], self.output_channel_block[
|
351 |
+
3], kernel_size=2, stride=1, padding=0, bias=False)
|
352 |
+
self.bn4_2 = nn.BatchNorm2d(self.output_channel_block[3])
|
353 |
+
|
354 |
+
def _make_layer(self, block, planes, blocks, stride=1):
|
355 |
+
downsample = None
|
356 |
+
if stride != 1 or self.inplanes != planes * block.expansion:
|
357 |
+
downsample = nn.Sequential(
|
358 |
+
nn.Conv2d(self.inplanes, planes * block.expansion,
|
359 |
+
kernel_size=1, stride=stride, bias=False),
|
360 |
+
nn.BatchNorm2d(planes * block.expansion),
|
361 |
+
)
|
362 |
+
|
363 |
+
layers = []
|
364 |
+
layers.append(block(self.inplanes, planes, stride, downsample))
|
365 |
+
self.inplanes = planes * block.expansion
|
366 |
+
for i in range(1, blocks):
|
367 |
+
layers.append(block(self.inplanes, planes))
|
368 |
+
|
369 |
+
return nn.Sequential(*layers)
|
370 |
+
|
371 |
+
def forward(self, x):
|
372 |
+
x = self.conv0_1(x)
|
373 |
+
x = self.bn0_1(x)
|
374 |
+
x = self.relu(x)
|
375 |
+
x = self.conv0_2(x)
|
376 |
+
x = self.bn0_2(x)
|
377 |
+
x = self.relu(x)
|
378 |
+
|
379 |
+
x = self.maxpool1(x)
|
380 |
+
x = self.layer1(x)
|
381 |
+
x = self.conv1(x)
|
382 |
+
x = self.bn1(x)
|
383 |
+
x = self.relu(x)
|
384 |
+
|
385 |
+
x = self.maxpool2(x)
|
386 |
+
x = self.layer2(x)
|
387 |
+
x = self.conv2(x)
|
388 |
+
x = self.bn2(x)
|
389 |
+
x = self.relu(x)
|
390 |
+
|
391 |
+
x = self.maxpool3(x)
|
392 |
+
x = self.layer3(x)
|
393 |
+
x = self.conv3(x)
|
394 |
+
x = self.bn3(x)
|
395 |
+
x = self.relu(x)
|
396 |
+
|
397 |
+
x = self.layer4(x)
|
398 |
+
x = self.conv4_1(x)
|
399 |
+
x = self.bn4_1(x)
|
400 |
+
x = self.relu(x)
|
401 |
+
x = self.conv4_2(x)
|
402 |
+
x = self.bn4_2(x)
|
403 |
+
x = self.relu(x)
|
404 |
+
|
405 |
+
return x
|
406 |
+
|
407 |
+
|
408 |
+
class BidirectionalLSTM(nn.Module):
|
409 |
+
|
410 |
+
def __init__(self, input_size, hidden_size, output_size):
|
411 |
+
super(BidirectionalLSTM, self).__init__()
|
412 |
+
self.rnn = nn.LSTM(input_size, hidden_size, bidirectional=True, batch_first=True)
|
413 |
+
self.linear = nn.Linear(hidden_size * 2, output_size)
|
414 |
+
|
415 |
+
def forward(self, input):
|
416 |
+
"""
|
417 |
+
input : visual feature [batch_size x T x input_size]
|
418 |
+
output : contextual feature [batch_size x T x output_size]
|
419 |
+
"""
|
420 |
+
try:
|
421 |
+
self.rnn.flatten_parameters()
|
422 |
+
except:
|
423 |
+
pass
|
424 |
+
recurrent, _ = self.rnn(input) # batch_size x T x input_size -> batch_size x T x (2*hidden_size)
|
425 |
+
output = self.linear(recurrent) # batch_size x T x output_size
|
426 |
+
return output
|
427 |
+
|
428 |
+
|
429 |
+
class Attention(nn.Module):
|
430 |
+
|
431 |
+
def __init__(self, input_size, hidden_size, num_classes):
|
432 |
+
super(Attention, self).__init__()
|
433 |
+
self.attention_cell = AttentionCell(input_size, hidden_size, num_classes)
|
434 |
+
self.hidden_size = hidden_size
|
435 |
+
self.num_classes = num_classes
|
436 |
+
self.generator = nn.Linear(hidden_size, num_classes)
|
437 |
+
|
438 |
+
def _char_to_onehot(self, input_char, onehot_dim=38):
|
439 |
+
input_char = input_char.unsqueeze(1)
|
440 |
+
batch_size = input_char.size(0)
|
441 |
+
one_hot = torch.FloatTensor(batch_size, onehot_dim).zero_().to(device)
|
442 |
+
one_hot = one_hot.scatter_(1, input_char, 1)
|
443 |
+
return one_hot
|
444 |
+
|
445 |
+
def forward(self, batch_H, text, is_train=True, batch_max_length=25):
|
446 |
+
"""
|
447 |
+
input:
|
448 |
+
batch_H : contextual_feature H = hidden state of encoder. [batch_size x num_steps x num_classes]
|
449 |
+
text : the text-index of each image. [batch_size x (max_length+1)]. +1 for [GO] token. text[:, 0] = [GO].
|
450 |
+
output: probability distribution at each step [batch_size x num_steps x num_classes]
|
451 |
+
"""
|
452 |
+
batch_size = batch_H.size(0)
|
453 |
+
num_steps = batch_max_length + 1 # +1 for [s] at end of sentence.
|
454 |
+
|
455 |
+
output_hiddens = torch.FloatTensor(batch_size, num_steps, self.hidden_size).fill_(0).to(device)
|
456 |
+
hidden = (torch.FloatTensor(batch_size, self.hidden_size).fill_(0).to(device),
|
457 |
+
torch.FloatTensor(batch_size, self.hidden_size).fill_(0).to(device))
|
458 |
+
|
459 |
+
if is_train:
|
460 |
+
for i in range(num_steps):
|
461 |
+
# one-hot vectors for a i-th char. in a batch
|
462 |
+
char_onehots = self._char_to_onehot(text[:, i], onehot_dim=self.num_classes)
|
463 |
+
# hidden : decoder's hidden s_{t-1}, batch_H : encoder's hidden H, char_onehots : one-hot(y_{t-1})
|
464 |
+
hidden, alpha = self.attention_cell(hidden, batch_H, char_onehots)
|
465 |
+
output_hiddens[:, i, :] = hidden[0] # LSTM hidden index (0: hidden, 1: Cell)
|
466 |
+
probs = self.generator(output_hiddens)
|
467 |
+
|
468 |
+
else:
|
469 |
+
targets = torch.LongTensor(batch_size).fill_(0).to(device) # [GO] token
|
470 |
+
probs = torch.FloatTensor(batch_size, num_steps, self.num_classes).fill_(0).to(device)
|
471 |
+
|
472 |
+
for i in range(num_steps):
|
473 |
+
char_onehots = self._char_to_onehot(targets, onehot_dim=self.num_classes)
|
474 |
+
hidden, alpha = self.attention_cell(hidden, batch_H, char_onehots)
|
475 |
+
probs_step = self.generator(hidden[0])
|
476 |
+
probs[:, i, :] = probs_step
|
477 |
+
_, next_input = probs_step.max(1)
|
478 |
+
targets = next_input
|
479 |
+
|
480 |
+
return probs # batch_size x num_steps x num_classes
|
481 |
+
|
482 |
+
|
483 |
+
class AttentionCell(nn.Module):
|
484 |
+
|
485 |
+
def __init__(self, input_size, hidden_size, num_embeddings):
|
486 |
+
super(AttentionCell, self).__init__()
|
487 |
+
self.i2h = nn.Linear(input_size, hidden_size, bias=False)
|
488 |
+
self.h2h = nn.Linear(hidden_size, hidden_size) # either i2i or h2h should have bias
|
489 |
+
self.score = nn.Linear(hidden_size, 1, bias=False)
|
490 |
+
self.rnn = nn.LSTMCell(input_size + num_embeddings, hidden_size)
|
491 |
+
self.hidden_size = hidden_size
|
492 |
+
|
493 |
+
def forward(self, prev_hidden, batch_H, char_onehots):
|
494 |
+
# [batch_size x num_encoder_step x num_channel] -> [batch_size x num_encoder_step x hidden_size]
|
495 |
+
batch_H_proj = self.i2h(batch_H)
|
496 |
+
prev_hidden_proj = self.h2h(prev_hidden[0]).unsqueeze(1)
|
497 |
+
e = self.score(torch.tanh(batch_H_proj + prev_hidden_proj)) # batch_size x num_encoder_step * 1
|
498 |
+
|
499 |
+
alpha = F.softmax(e, dim=1)
|
500 |
+
context = torch.bmm(alpha.permute(0, 2, 1), batch_H).squeeze(1) # batch_size x num_channel
|
501 |
+
concat_context = torch.cat([context, char_onehots], 1) # batch_size x (num_channel + num_embedding)
|
502 |
+
cur_hidden = self.rnn(concat_context, prev_hidden)
|
503 |
+
return cur_hidden, alpha
|
504 |
+
|
505 |
+
|
506 |
+
class Model(nn.Module):
|
507 |
+
|
508 |
+
def __init__(self, input_channel, output_channel, hidden_size, num_class):
|
509 |
+
super(Model, self).__init__()
|
510 |
+
|
511 |
+
|
512 |
+
""" FeatureExtraction """
|
513 |
+
self.FeatureExtraction = VGG_FeatureExtractor(input_channel, output_channel)
|
514 |
+
self.FeatureExtraction_output = output_channel # int(imgH/16-1) * 512
|
515 |
+
self.AdaptiveAvgPool = nn.AdaptiveAvgPool2d((None, 1)) # Transform final (imgH/16-1) -> 1
|
516 |
+
|
517 |
+
""" Sequence modeling"""
|
518 |
+
self.SequenceModeling = nn.Sequential(
|
519 |
+
BidirectionalLSTM(self.FeatureExtraction_output, hidden_size, hidden_size),
|
520 |
+
BidirectionalLSTM(hidden_size, hidden_size, hidden_size))
|
521 |
+
self.SequenceModeling_output = hidden_size
|
522 |
+
|
523 |
+
|
524 |
+
self.Prediction = nn.Linear(self.SequenceModeling_output, num_class)
|
525 |
+
|
526 |
+
def forward(self, input, text):
|
527 |
+
|
528 |
+
""" Feature extraction stage """
|
529 |
+
visual_feature = self.FeatureExtraction(input)
|
530 |
+
visual_feature = self.AdaptiveAvgPool(visual_feature.permute(0, 3, 1, 2)) # [b, c, h, w] -> [b, w, c, h]
|
531 |
+
visual_feature = visual_feature.squeeze(3)
|
532 |
+
|
533 |
+
""" Sequence modeling stage """
|
534 |
+
contextual_feature = self.SequenceModeling(visual_feature)
|
535 |
+
|
536 |
+
prediction = self.Prediction(contextual_feature.contiguous())
|
537 |
+
|
538 |
+
return prediction
|
models/best_norm_ED.yaml
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
number: '0123456789'
|
2 |
+
symbol: "!?.,:;'#()<>+-/*=%$»« "
|
3 |
+
lang_char: 'АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁабвгдежзийклмнопрстуфхцчшщъыьэюяёӘҒҚҢӨҰҮІҺәғқңөұүіһ'
|
4 |
+
experiment_name: 'kz_synthtiger_v6'
|
5 |
+
train_data: '../../synthtiger_kz/results/train_v6'
|
6 |
+
valid_data: '../../synthtiger_kz/results/test_v6'
|
7 |
+
manualSeed: 1111
|
8 |
+
workers: 6
|
9 |
+
batch_size: 256 #32
|
10 |
+
num_iter: 100000
|
11 |
+
valInterval: 1000
|
12 |
+
saved_model: '' #'saved_models/en_filtered/iter_300000.pth'
|
13 |
+
FT: False
|
14 |
+
optim: False # default is Adadelta
|
15 |
+
lr: 1.
|
16 |
+
beta1: 0.9
|
17 |
+
rho: 0.95
|
18 |
+
eps: 0.00000001
|
19 |
+
grad_clip: 5
|
20 |
+
#Data processing
|
21 |
+
select_data: 'images' # this is dataset folder in train_data
|
22 |
+
batch_ratio: '1'
|
23 |
+
total_data_usage_ratio: 1.0
|
24 |
+
batch_max_length: 34
|
25 |
+
imgH: 64
|
26 |
+
imgW: 600
|
27 |
+
rgb: False
|
28 |
+
sensitive: True
|
29 |
+
PAD: True
|
30 |
+
contrast_adjust: 0.0
|
31 |
+
data_filtering_off: False
|
32 |
+
# Model Architecture
|
33 |
+
Transformation: 'None'
|
34 |
+
FeatureExtraction: 'VGG'
|
35 |
+
SequenceModeling: 'BiLSTM'
|
36 |
+
Prediction: 'CTC'
|
37 |
+
num_fiducial: 20
|
38 |
+
input_channel: 1
|
39 |
+
output_channel: 256
|
40 |
+
hidden_size: 256
|
41 |
+
decode: 'greedy'
|
42 |
+
new_prediction: False
|
43 |
+
freeze_FeatureFxtraction: False
|
44 |
+
freeze_SequenceModeling: False
|
45 |
+
|
46 |
+
network_params:
|
47 |
+
input_channel: 1
|
48 |
+
output_channel: 256
|
49 |
+
hidden_size: 256
|
50 |
+
lang_list:
|
51 |
+
- 'en'
|
52 |
+
character_list: 0123456789!?.,:;'#()<>+-/*=%$»« АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁабвгдежзийклмнопрстуфхцчшщъыьэюяёӘҒҚҢӨҰҮІҺәғқңөұүіһ
|
models/craft_mlt_25k.pth
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4a5efbfb48b4081100544e75e1e2b57f8de3d84f213004b14b85fd4b3748db17
|
3 |
+
size 83152330
|