-
Notifications
You must be signed in to change notification settings - Fork 1
/
ocr.py
162 lines (135 loc) · 4.97 KB
/
ocr.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
import argparse
import os
import cv2
import imutils
import numpy as np
import pytesseract
from imutils.perspective import four_point_transform
from financial_advice import categorize_expenses
import json
def perform_ocr(img: np.ndarray):
img_orig = cv2.imdecode(img, cv2.IMREAD_COLOR)
image = img_orig.copy()
image = imutils.resize(image, width=500)
ratio = img_orig.shape[1] / float(image.shape[1])
# convert the image to grayscale, blur it slightly, and then apply
# edge detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(
gray,
(
5,
5,
),
0,
)
edged = cv2.Canny(blurred, 75, 200)
# find contours in the edge map and sort them by size in descending
# order
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# initialize a contour that corresponds to the receipt outline
receiptCnt = None
# loop over the contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points, then we can
# assume we have found the outline of the receipt
if len(approx) == 4:
receiptCnt = approx
break
# if the receipt contour is empty then our script could not find the
# outline and we should be notified
if receiptCnt is None:
raise Exception(
(
"Could not find receipt outline. "
"Try debugging your edge detection and contour steps."
)
)
# apply a four-point perspective transform to the *original* image to
# obtain a top-down bird's-eye view of the receipt
receipt = four_point_transform(img_orig, receiptCnt.reshape(4, 2) * ratio)
# apply OCR to the receipt image by assuming column data, ensuring
# the text is *concatenated across the row* (additionally, for your
# own images you may need to apply additional processing to cleanup
# the image, including resizing, thresholding, etc.)
options = "--psm 6"
text = pytesseract.image_to_string(
cv2.cvtColor(receipt, cv2.COLOR_BGR2RGB), config=options
)
return text
def getText(image_path):
img_orig = cv2.imread(image_path)
image = img_orig.copy()
image = imutils.resize(image, width=500)
ratio = img_orig.shape[1] / float(image.shape[1])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(
gray,
(
5,
5,
),
0,
)
edged = cv2.Canny(blurred, 75, 200)
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# initialize a contour that corresponds to the receipt outline
receiptCnt = None
# loop over the contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points, then we can
# assume we have found the outline of the receipt
if len(approx) == 4:
receiptCnt = approx
break
# cv2.drawContours(image, [receiptCnt], -1, (0, 255, 0), 2)
# cv2.imwrite('image_with_outline.jpg', image)
# cv2.imshow("Receipt Outline", image)
# cv2.waitKey(0)
# if the receipt contour is empty then our script could not find the
# outline and we should be notified
if receiptCnt is None:
raise Exception(
(
"Could not find receipt outline. "
"Try debugging your edge detection and contour steps."
)
)
# apply a four-point perspective transform to the *original* image to
# obtain a top-down bird's-eye view of the receipt
receipt = img_orig# four_point_transform(img_orig, receiptCnt.reshape(4, 2) * ratio)
cv2.imwrite('transformed_receipt.jpg', receipt)
# apply OCR to the receipt image by assuming column data, ensuring
# the text is *concatenated across the row* (additionally, for your
# own images you may need to apply additional processing to cleanup
# the image, including resizing, thresholding, etc.)
options = "--psm 6"
text = pytesseract.image_to_string(
cv2.cvtColor(receipt, cv2.COLOR_BGR2RGB), config=options
)
# show the raw output of the OCR process
return text
def getJson(image_path):
text = getText(image_path)
response = categorize_expenses(text)
content = str(response)
print("\n\n\n\n\n")
print(content)
print("\n\n\n\n\n")
json_data = json.loads(content)
return json_data
def main():
result = getJson(image_path="exampleHard.jpeg")
print(result)
if __name__ == "__main__":
main()