Sanjayraju30 commited on
Commit
712c074
·
verified ·
1 Parent(s): f823764

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +14 -12
ocr_engine.py CHANGED
@@ -9,27 +9,29 @@ def extract_weight_from_image(pil_img):
9
  try:
10
  img = np.array(pil_img)
11
 
12
- # Resize for consistency
13
  if img.shape[1] > 1000:
14
  img = cv2.resize(img, (1000, int(img.shape[0] * 1000 / img.shape[1])))
15
 
16
- # Preprocessing for 7-segment digital font
17
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
18
- gray = cv2.resize(gray, None, fx=3, fy=3, interpolation=cv2.INTER_LINEAR)
19
- blur = cv2.GaussianBlur(gray, (3, 3), 0)
20
- _, thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
21
 
22
- # Optional inversion for black background with white digits
23
- white_pct = np.mean(thresh > 127)
24
- if white_pct < 0.5:
 
 
25
  thresh = cv2.bitwise_not(thresh)
26
 
27
  # OCR
28
  result = reader.readtext(thresh, detail=0)
29
- combined_text = " ".join(result).strip()
30
- print("OCR Text:", combined_text)
31
 
32
- # Match number like 25, 65.2, 18.89 etc.
33
  match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", combined_text)
34
  if match:
35
  weight = match.group(1)
@@ -38,5 +40,5 @@ def extract_weight_from_image(pil_img):
38
  return "No weight detected kg", 0.0
39
 
40
  except Exception as e:
 
41
  return f"Error: {str(e)}", 0.0
42
-
 
9
  try:
10
  img = np.array(pil_img)
11
 
12
+ # Resize if image is large
13
  if img.shape[1] > 1000:
14
  img = cv2.resize(img, (1000, int(img.shape[0] * 1000 / img.shape[1])))
15
 
16
+ # Convert to grayscale and upscale
17
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
18
+ gray = cv2.resize(gray, None, fx=4, fy=4, interpolation=cv2.INTER_CUBIC)
19
+ gray = cv2.GaussianBlur(gray, (5, 5), 0)
20
+ gray = cv2.equalizeHist(gray)
21
 
22
+ # Thresholding
23
+ _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
24
+
25
+ # Invert if needed
26
+ if np.mean(thresh > 127) < 0.5:
27
  thresh = cv2.bitwise_not(thresh)
28
 
29
  # OCR
30
  result = reader.readtext(thresh, detail=0)
31
+ print("🔍 OCR Text:", result)
32
+ combined_text = " ".join(result)
33
 
34
+ # Extract weight
35
  match = re.search(r"(\d{1,4}(?:\.\d{1,2})?)", combined_text)
36
  if match:
37
  weight = match.group(1)
 
40
  return "No weight detected kg", 0.0
41
 
42
  except Exception as e:
43
+ print("❌ OCR Error:", e)
44
  return f"Error: {str(e)}", 0.0