Sanjayraju30 commited on
Commit
7f861bc
·
verified ·
1 Parent(s): 9c19d9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -19
app.py CHANGED
@@ -1,39 +1,43 @@
1
  import gradio as gr
2
- import easyocr
3
- import re
4
  import cv2
5
  import numpy as np
6
- from PIL import Image
7
  from datetime import datetime
 
 
8
 
9
- reader = easyocr.Reader(['en'], gpu=False)
10
 
11
  def detect_weight(image):
12
  if image is None:
13
  return "No image uploaded", "N/A", None
14
 
15
- # Convert PIL to OpenCV
16
  image_np = np.array(image)
17
- gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
18
 
19
- # Optional: Enhance contrast
 
20
  gray = cv2.equalizeHist(gray)
 
 
 
 
21
 
22
- # OCR
23
- results = reader.readtext(gray, detail=1)
24
 
25
- weight = None
26
- max_conf = 0
27
- for (bbox, text, conf) in results:
28
- text = text.strip()
29
- match = re.search(r'\d+\.\d+', text)
30
- if match and conf > max_conf:
31
- weight = match.group()
32
- max_conf = conf
33
 
34
- if weight:
35
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
36
- return f"Weight: {weight} kg (Confidence: {round(max_conf*100, 2)}%)", now, image
37
  else:
38
  return "No weight detected kg (Confidence: 0.0%)", "N/A", image
39
 
 
1
  import gradio as gr
 
 
2
  import cv2
3
  import numpy as np
4
+ from paddleocr import PaddleOCR
5
  from datetime import datetime
6
+ import re
7
+ from PIL import Image
8
 
9
+ ocr = PaddleOCR(use_angle_cls=True, lang='en') # Better for clean numbers
10
 
11
  def detect_weight(image):
12
  if image is None:
13
  return "No image uploaded", "N/A", None
14
 
15
+ # Convert to OpenCV format
16
  image_np = np.array(image)
 
17
 
18
+ # Preprocessing: Convert to grayscale, enhance contrast
19
+ gray = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)
20
  gray = cv2.equalizeHist(gray)
21
+ gray = cv2.cvtColor(gray, cv2.COLOR_GRAY2RGB) # Convert back to 3 channel for PaddleOCR
22
+
23
+ # Run OCR
24
+ result = ocr.ocr(gray, cls=True)
25
 
26
+ best_match = None
27
+ best_conf = 0
28
 
29
+ for line in result:
30
+ for box in line:
31
+ text = box[1][0]
32
+ conf = box[1][1]
33
+ match = re.search(r"\d+\.\d+", text)
34
+ if match and conf > best_conf:
35
+ best_match = match.group()
36
+ best_conf = conf
37
 
38
+ if best_match:
39
  now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
40
+ return f"Weight: {best_match} kg (Confidence: {round(best_conf*100, 2)}%)", now, image
41
  else:
42
  return "No weight detected kg (Confidence: 0.0%)", "N/A", image
43