-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOCR automator.py
177 lines (123 loc) · 4.25 KB
/
OCR automator.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
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 22:45:50 2017
@author: rounayak
"""
import argparse
import cv2
from PIL import Image
import os
import pandas as pd
from tqdm import tqdm
# initialize the list of reference points and boolean indicating
# whether cropping is being performed or not
refPt = []
cropping = False
def click_and_crop(event, x, y, flags, param):
# grab references to the global variables
global refPt, cropping
# if the left mouse button was clicked, record the starting
# (x, y) coordinates and indicate that cropping is being
# performed
if event == cv2.EVENT_LBUTTONDOWN:
refPt = [(x, y)]
cropping = True
# check to see if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates and indicate that
# the cropping operation is finished
refPt.append((x, y))
cropping = False
# draw a rectangle around the region of interest
cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
cv2.imshow("image", image)
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="Path to the image")
args = vars(ap.parse_args())
m=str(args.values()).strip('[').strip(']').strip("'")
print(m)
size=1920,1357
from PIL import Image
#im = Image.open('1.tif')
im = Image.open(m)
im.save('dum.png')
im = Image.open("dum.png")
im_resized = im.resize(size, Image.ANTIALIAS)
im_resized.save("dum.png", "PNG")
# load the image, clone it, and setup the mouse callback function
#image = cv2.imread(args["image"])
image = cv2.imread('dum.png')
clone = image.copy()
cv2.namedWindow("image",cv2.WINDOW_NORMAL)
cv2.setMouseCallback("image", click_and_crop)
# keep looping until the 'q' key is pressed
while True:
# display the image and wait for a keypress
cv2.imshow("image", image)
key = cv2.waitKey(1) & 0xFF
# if the 'r' key is pressed, reset the cropping region
if key == ord("r"):
image = clone.copy()
# if the 'c' key is pressed, break from the loop
elif key == ord("c"):
break
# if there are two reference points, then crop the region of interest
# from the image and display it
if len(refPt) == 2:
roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
print(refPt[0][1],refPt[0][0],refPt[1][1],refPt[1][0])
cv2.imshow("ROI", roi)
cv2.waitKey(0)
# close all open windows
cv2.destroyAllWindows()
def looper(f,df):
import pandas as pd
size=1920,1357
from PIL import Image
im = Image.open(f)
im.resize(size, Image.ANTIALIAS).save('dum.png',"PNG")
import os
import cv2
img = cv2.imread("dum.png")
crop_img = img[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
cv2.imwrite("cropped.png", crop_img)
import pytesseract
from PIL import Image
pytesseract.pytesseract.tesseract_cmd ='C:\\Program Files (x86)\\Tesseract-OCR\\tesseract'
tessdata_dir_config = '--tessdata-dir "C:\\Program Files (x86)\\Tesseract-OCR\\tessdata"'
y=Image.open('cropped.png')
output= pytesseract.image_to_string(y)
output1=output.encode('utf-8')
#print output
#file = open("output1.txt","w")
#file.write(output)
#file.close()
x1=len(df.index)
#print(x1)
df.loc[x1,'File']=f
df.loc[x1,'Value']=output1
return(df)
# df.loc[x1,'Value']=output.split[1]
#df.to_csv("Extraction.csv",index=False)
ext='f'
dir_path = os.getcwd()
from PIL import Image
df=pd.DataFrame({'File':[],'Key':[],'Value':[]})
df.to_csv("Extraction.csv", index= False)
files = os.listdir(dir_path)
files=[i for i in files if i.endswith(ext)]
[looper(x,df) for x in tqdm(files)]
df.to_csv("Extraction.csv",index=False)
df=pd.read_csv("Extraction.csv")
x=len(df.index)
df['Key']='Date'
df.to_csv("Extraction.csv",index=False)
df=pd.read_csv("Extraction.csv")
x=len(df.index)
for i in range(x):
df.loc[i,'Value']='.'.join([x.strip() for x in str(df.loc[i,'Value']).replace(",",".").split('.')])
df.to_csv("Extraction2.csv",index=False)
os.remove('Extraction.csv')
os.remove('dum.png')
os.remove('cropped.png')