Sanjayraju30 commited on
Commit
005d086
·
verified ·
1 Parent(s): 3ca006e

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +12 -6
ocr_engine.py CHANGED
@@ -3,22 +3,27 @@ import numpy as np
3
  import cv2
4
  import re
5
 
6
- # Load OCR model once
7
  reader = easyocr.Reader(['en'], gpu=False)
8
 
9
  def enhance_image(img):
10
- # Enlarge and convert to grayscale
11
- img = cv2.resize(img, None, fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
 
 
 
 
 
 
12
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
13
 
14
  # Denoise
15
  gray = cv2.fastNlMeansDenoising(gray, h=15)
16
 
17
  # Sharpen
18
- kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
19
  sharp = cv2.filter2D(gray, -1, kernel)
20
 
21
- # Contrast enhance
22
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
23
  contrast = clahe.apply(sharp)
24
 
@@ -36,7 +41,8 @@ def extract_weight_from_image(pil_img):
36
  weight_candidates = []
37
 
38
  for _, text, conf in results:
39
- cleaned = text.lower().replace("kg", "").replace("kgs", "")
 
40
  cleaned = cleaned.replace("o", "0").replace("s", "5").replace("g", "9")
41
  cleaned = re.sub(r"[^\d\.]", "", cleaned)
42
 
 
3
  import cv2
4
  import re
5
 
 
6
  reader = easyocr.Reader(['en'], gpu=False)
7
 
8
  def enhance_image(img):
9
+ # Resize big images
10
+ max_dim = 1000
11
+ height, width = img.shape[:2]
12
+ if max(height, width) > max_dim:
13
+ scale = max_dim / max(height, width)
14
+ img = cv2.resize(img, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
15
+
16
+ # Grayscale
17
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
18
 
19
  # Denoise
20
  gray = cv2.fastNlMeansDenoising(gray, h=15)
21
 
22
  # Sharpen
23
+ kernel = np.array([[0, -1, 0], [-1, 5,-1], [0, -1, 0]])
24
  sharp = cv2.filter2D(gray, -1, kernel)
25
 
26
+ # Contrast
27
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
28
  contrast = clahe.apply(sharp)
29
 
 
41
  weight_candidates = []
42
 
43
  for _, text, conf in results:
44
+ cleaned = text.lower()
45
+ cleaned = cleaned.replace("kg", "").replace("kgs", "")
46
  cleaned = cleaned.replace("o", "0").replace("s", "5").replace("g", "9")
47
  cleaned = re.sub(r"[^\d\.]", "", cleaned)
48