Rammohan0504 commited on
Commit
25728eb
·
verified ·
1 Parent(s): deda0a5

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +15 -4
ocr_engine.py CHANGED
@@ -5,18 +5,29 @@ import re
5
  reader = easyocr.Reader(['en'], gpu=False)
6
 
7
  def extract_weight_from_image(img_cv):
8
- # Resize to help with clarity
9
  img = cv2.resize(img_cv, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC)
10
 
11
- # Convert to grayscale if needed
12
  if len(img.shape) == 3:
13
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
14
 
 
 
 
 
 
 
 
 
 
15
  results = reader.readtext(img)
16
 
17
- raw_text = " ".join([text for _, text, _ in results])
18
- matches = re.findall(r'\d+\.\d+|\d+', raw_text)
 
19
 
 
20
  weight = matches[0] if matches else "0.0"
21
  confidence = int(results[0][2] * 100) if results else 0
22
 
 
5
  reader = easyocr.Reader(['en'], gpu=False)
6
 
7
  def extract_weight_from_image(img_cv):
8
+ # Resize for clarity
9
  img = cv2.resize(img_cv, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC)
10
 
11
+ # Convert to grayscale
12
  if len(img.shape) == 3:
13
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
14
 
15
+ # Adaptive threshold to boost contrast
16
+ img = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
17
+ cv2.THRESH_BINARY, 11, 3)
18
+
19
+ # Morphological close to unify digits
20
+ kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
21
+ img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
22
+
23
+ # OCR detection
24
  results = reader.readtext(img)
25
 
26
+ # Filter only short, confident numeric candidates
27
+ filtered = [text for _, text, conf in results if len(text.strip()) <= 5 and conf > 0.4]
28
+ raw_text = " ".join(filtered)
29
 
30
+ matches = re.findall(r"\d+\.\d+|\d+", raw_text)
31
  weight = matches[0] if matches else "0.0"
32
  confidence = int(results[0][2] * 100) if results else 0
33