Skip to content

Commit 9dc8098

Browse files
committed
Add OCR function
1 parent f358f33 commit 9dc8098

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

server/crop.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import cv2
2+
import numpy as np
3+
from matplotlib import pyplot as plt
4+
from pytesseract import image_to_string
5+
6+
def ocr(filename):
7+
img = cv2.imread(f'static/images/cheques/{filename}')
8+
9+
max_brightness = 0
10+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
11+
canvas = img.copy()
12+
#ret,thresh = cv2.threshold(gray,199,255,1)
13+
blur = cv2.medianBlur(img,5)
14+
edged = cv2.Canny(blur, 25, 70)
15+
contours,h= cv2.findContours(edged,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
16+
17+
cv2.drawContours(img, contours,-1, (0,255,0), 3)
18+
19+
for cnt in contours:
20+
rect = cv2.boundingRect(cnt)
21+
x, y, w, h = rect
22+
if w*h > 40000:
23+
mask = np.zeros(img.shape, np.uint8)
24+
mask[y:y+h, x:x+w] = img[y:y+h, x:x+w]
25+
brightness = np.sum(mask)
26+
if brightness > max_brightness:
27+
brightest_rectangle = rect
28+
max_brightness = brightness
29+
30+
x, y, w, h = brightest_rectangle
31+
crop_img = img[y:y+h, x:x+w]
32+
33+
edges = cv2.Canny(crop_img,101,200)
34+
35+
crop_img = img[y:y+h, x:x+w]
36+
cheque = {}
37+
38+
cheque['date'] = { 'bounds': (int(h*0.07), int(h*0.14), int(w*0.75),int(w*0.965) )}
39+
cheque['name'] = { 'bounds': (int(h*0.17), int(h*0.27), int(w*0.07),int(w*0.6) )}
40+
cheque['amt_words1'] = { 'bounds': (int(h*0.28), int(h*0.36), int(w*0.15),int(w*0.72) )}
41+
cheque['amt_words2'] = { 'bounds': (int(h*0.36), int(h*0.45), int(w*0.03),int(w*0.65) )}
42+
cheque['amt_no'] = { 'bounds': (int(h*0.36), int(h*0.45), int(w*0.77),int(w*0.97) )}
43+
cheque['acc_no'] = { 'bounds': (int(h*0.49), int(h*0.55), int(w*0.09),int(w*0.40) )}
44+
cheque['micr_code'] = { 'bounds': (int(h*0.85), int(h*0.95), int(w*0.2 ),int(w*0.75) )}
45+
46+
out = cv2.cvtColor(edges, cv2.COLOR_GRAY2RGB)
47+
text = {}
48+
49+
for f in cheque:
50+
y0, y1, x0, x1 = cheque[f]['bounds']
51+
crop_field = crop_img[y0:y1,x0:x1]
52+
cv2.rectangle(out, (x0,y0),(x1,y1), color=(0,255,0), thickness=3 )
53+
text[f] = image_to_string(crop_field)
54+
print(f, ':' , text[f])
55+
56+
cv2.imwrite(f'static/images/canny/{filename}',out)
57+
return text
168 KB
Loading

0 commit comments

Comments
 (0)