Sanjayraju30 commited on
Commit
1379dcc
·
verified ·
1 Parent(s): 6a56695

Update ocr_engine.py

Browse files
Files changed (1) hide show
  1. ocr_engine.py +5 -5
ocr_engine.py CHANGED
@@ -9,26 +9,26 @@ def extract_weight_from_image(pil_img):
9
  try:
10
  img = np.array(pil_img)
11
 
12
- # Grayscale + resize
13
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
14
  gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
15
 
16
  # Histogram equalization
17
  gray = cv2.equalizeHist(gray)
18
 
19
- # Adaptive threshold
20
  thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
21
  cv2.THRESH_BINARY, 11, 2)
22
 
23
- # Invert colors (LCD digits are usually dark on light)
24
  thresh = cv2.bitwise_not(thresh)
25
 
26
- # OCR
27
  result = reader.readtext(thresh, detail=0)
28
  combined_text = " ".join(result)
29
  print("OCR Text:", combined_text)
30
 
31
- # Match weight pattern (e.g. 52.30, 003.2, 250)
32
  match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", combined_text)
33
  if match:
34
  return match.group(), 95.0
 
9
  try:
10
  img = np.array(pil_img)
11
 
12
+ # Convert to grayscale and resize for better clarity
13
  gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
14
  gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
15
 
16
  # Histogram equalization
17
  gray = cv2.equalizeHist(gray)
18
 
19
+ # Adaptive threshold to enhance text
20
  thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
21
  cv2.THRESH_BINARY, 11, 2)
22
 
23
+ # Invert for LCD-like contrast
24
  thresh = cv2.bitwise_not(thresh)
25
 
26
+ # OCR read
27
  result = reader.readtext(thresh, detail=0)
28
  combined_text = " ".join(result)
29
  print("OCR Text:", combined_text)
30
 
31
+ # Regex to match weight like 25, 46.5, 75.45 etc.
32
  match = re.search(r"\b\d{2,4}\.?\d{0,2}\b", combined_text)
33
  if match:
34
  return match.group(), 95.0