Sanjayraju30 commited on
Commit
376b89d
·
verified ·
1 Parent(s): dc51a98

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +6 -10
ocr_engine.py CHANGED
@@ -12,16 +12,12 @@ def extract_weight_from_image(pil_img):
12
  # Convert to grayscale
13
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
14
 
15
- # Enhance contrast
16
- gray = cv2.equalizeHist(gray)
17
-
18
- # Resize to enhance small text
19
  gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
 
20
 
21
- # Add light blur to reduce noise
22
  gray = cv2.GaussianBlur(gray, (3, 3), 0)
23
-
24
- # Invert for LCD screens with dark backgrounds
25
  inverted = cv2.bitwise_not(gray)
26
 
27
  # OCR
@@ -29,12 +25,12 @@ def extract_weight_from_image(pil_img):
29
  combined_text = " ".join(result)
30
  print("OCR Result:", combined_text)
31
 
32
- # Try to detect weight pattern like "25kg" or "25.3kg"
33
- match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)\s?(kg)", combined_text, re.IGNORECASE)
34
  if match:
35
  return f"{match.group(1)} kg", 95.0
36
 
37
- # Fallback: detect numbers only
38
  fallback = re.search(r"\d{1,4}(?:\.\d{1,2})?", combined_text)
39
  if fallback:
40
  return f"{fallback.group(0)} kg", 75.0
 
12
  # Convert to grayscale
13
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
14
 
15
+ # Resize and enhance contrast
 
 
 
16
  gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
17
+ gray = cv2.equalizeHist(gray)
18
 
19
+ # Reduce noise and invert for LCD displays
20
  gray = cv2.GaussianBlur(gray, (3, 3), 0)
 
 
21
  inverted = cv2.bitwise_not(gray)
22
 
23
  # OCR
 
25
  combined_text = " ".join(result)
26
  print("OCR Result:", combined_text)
27
 
28
+ # Primary match: e.g., 25kg, 75.45 kg
29
+ match = re.search(r"(\d{1,3}(?:\.\d{1,2})?)\s?(kg|KG|Kg)", combined_text)
30
  if match:
31
  return f"{match.group(1)} kg", 95.0
32
 
33
+ # Fallback: just numbers (assume it's in kg)
34
  fallback = re.search(r"\d{1,4}(?:\.\d{1,2})?", combined_text)
35
  if fallback:
36
  return f"{fallback.group(0)} kg", 75.0