Sanjayraju30 commited on
Commit
8c624d2
Β·
verified Β·
1 Parent(s): adab0b4

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +16 -27
ocr_engine.py CHANGED
@@ -3,18 +3,16 @@ import re
3
  import cv2
4
  from PIL import Image
5
  import easyocr
6
- import os
7
 
8
- # βœ… Initialize OCR reader only once
9
  reader = easyocr.Reader(['en'], gpu=False)
10
 
11
  def preprocess_image(image):
12
  """
13
- Preprocess the image to improve OCR detection.
14
- Converts to grayscale and applies adaptive threshold.
15
  """
16
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
17
- # Apply adaptive threshold to isolate digits better
18
  thresh = cv2.adaptiveThreshold(
19
  gray, 255,
20
  cv2.ADAPTIVE_THRESH_MEAN_C,
@@ -25,43 +23,34 @@ def preprocess_image(image):
25
 
26
  def extract_weight_from_image(pil_image):
27
  try:
28
- # βœ… Step 1: Convert to OpenCV format
29
  image = np.array(pil_image.convert("RGB"))
30
 
31
- # βœ… Step 2: Preprocess image
32
  processed = preprocess_image(image)
33
 
34
- # βœ… Step 3: Optional - Save debug image
35
  debug_path = "debug_processed_image.png"
36
  Image.fromarray(processed).save(debug_path)
37
- print(f"[DEBUG] Saved preprocessed image to {debug_path}")
38
 
39
- # βœ… Step 4: Run EasyOCR
40
  result = reader.readtext(processed)
41
 
42
  print("πŸ” OCR Results:")
43
- for r in result:
44
- print(f" β€’ Text: '{r[1]}' | Confidence: {r[2]*100:.2f}%")
45
-
46
- # βœ… Step 5: Look for a decimal number like 53.25
47
- weight = None
48
- confidence = 0.0
49
 
 
50
  for detection in result:
51
- text = detection[1].replace(",", ".") # Handle comma decimal (if any)
52
  conf = detection[2]
53
-
54
- # Look for numbers like 53.25 or 100
55
- match = re.search(r"\b\d{1,3}(\.\d{1,2})?\b", text)
56
  if match:
57
- weight = match.group()
58
- confidence = conf
59
- break
60
 
61
- if weight:
62
- return weight, round(confidence * 100, 2)
63
- else:
64
- return "No weight detected", 0.0
65
 
66
  except Exception as e:
67
  print(f"❌ OCR Error: {e}")
 
3
  import cv2
4
  from PIL import Image
5
  import easyocr
 
6
 
7
+ # βœ… Initialize EasyOCR Reader once
8
  reader = easyocr.Reader(['en'], gpu=False)
9
 
10
  def preprocess_image(image):
11
  """
12
+ Convert to grayscale and apply adaptive thresholding
13
+ to enhance contrast for digital scale OCR.
14
  """
15
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
 
16
  thresh = cv2.adaptiveThreshold(
17
  gray, 255,
18
  cv2.ADAPTIVE_THRESH_MEAN_C,
 
23
 
24
  def extract_weight_from_image(pil_image):
25
  try:
26
+ # βœ… Convert PIL image to OpenCV format
27
  image = np.array(pil_image.convert("RGB"))
28
 
29
+ # βœ… Preprocess image
30
  processed = preprocess_image(image)
31
 
32
+ # βœ… Optional: Save debug image for troubleshooting
33
  debug_path = "debug_processed_image.png"
34
  Image.fromarray(processed).save(debug_path)
35
+ print(f"[DEBUG] Preprocessed image saved to: {debug_path}")
36
 
37
+ # βœ… Perform OCR using EasyOCR
38
  result = reader.readtext(processed)
39
 
40
  print("πŸ” OCR Results:")
41
+ for detection in result:
42
+ print(f" β€’ Text: '{detection[1]}' | Confidence: {detection[2]*100:.2f}%")
 
 
 
 
43
 
44
+ # βœ… Extract first matching numeric value
45
  for detection in result:
46
+ text = detection[1].replace(",", ".") # normalize decimal
47
  conf = detection[2]
48
+ match = re.search(r"\b\d{1,4}(\.\d{1,2})?\b", text)
 
 
49
  if match:
50
+ return match.group(), round(conf * 100, 2)
 
 
51
 
52
+ # ❌ No weight found
53
+ return "No weight detected", 0.0
 
 
54
 
55
  except Exception as e:
56
  print(f"❌ OCR Error: {e}")