Spaces:
Sleeping
Sleeping
Update weight_detector.py
Browse files- weight_detector.py +90 -77
weight_detector.py
CHANGED
@@ -2,55 +2,60 @@ import cv2
|
|
2 |
import numpy as np
|
3 |
import easyocr
|
4 |
import re
|
5 |
-
from typing import Tuple, List, Optional
|
6 |
from PIL import Image, ImageDraw
|
7 |
import pytz
|
8 |
from datetime import datetime
|
|
|
9 |
|
10 |
class WeightDetector:
|
11 |
def __init__(self):
|
12 |
-
"""
|
13 |
self.reader = easyocr.Reader(
|
14 |
['en'],
|
15 |
gpu=True,
|
16 |
model_storage_directory='model',
|
17 |
-
download_enabled=True
|
|
|
18 |
)
|
19 |
self.ist = pytz.timezone('Asia/Kolkata')
|
20 |
-
|
21 |
def get_current_ist(self) -> str:
|
22 |
-
"""Get current time
|
23 |
-
return datetime.now(self.ist).strftime('%Y-%m-%d %H:%M:%S
|
24 |
-
|
25 |
-
def
|
26 |
-
"""
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
28 |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
29 |
|
30 |
-
#
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
37 |
|
38 |
-
#
|
39 |
-
|
|
|
40 |
|
41 |
-
return
|
42 |
-
|
43 |
-
def
|
44 |
-
"""
|
45 |
-
|
46 |
-
text = text.replace(' ', '').replace(',', '.').lower()
|
47 |
|
48 |
-
# Patterns for digital
|
49 |
patterns = [
|
50 |
-
r'(\d+\.\d+)[
|
51 |
-
r'(\d+)[
|
52 |
-
r'(\d+\.\d+)',
|
53 |
-
r'(\d+)'
|
54 |
]
|
55 |
|
56 |
for pattern in patterns:
|
@@ -58,85 +63,93 @@ class WeightDetector:
|
|
58 |
if match:
|
59 |
try:
|
60 |
value = float(match.group(1))
|
61 |
-
|
62 |
-
|
63 |
-
return value * 1000 # Convert kg to g
|
64 |
return value
|
65 |
except ValueError:
|
66 |
continue
|
67 |
return None
|
68 |
-
|
69 |
-
def detect_weight(self, image_path: str) ->
|
70 |
-
"""
|
71 |
try:
|
72 |
-
# Read image
|
73 |
img = Image.open(image_path).convert("RGB")
|
74 |
img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
75 |
|
76 |
-
#
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
-
#
|
|
|
|
|
|
|
80 |
results = self.reader.readtext(
|
81 |
processed,
|
|
|
82 |
paragraph=False,
|
83 |
-
|
84 |
-
|
85 |
-
width_ths=2.0,
|
86 |
-
text_threshold=0.7
|
87 |
)
|
88 |
|
89 |
-
#
|
90 |
detected_weights = []
|
91 |
for (bbox, text, prob) in results:
|
92 |
-
weight = self.
|
93 |
-
if weight
|
94 |
detected_weights.append({
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
})
|
100 |
|
101 |
-
#
|
102 |
-
draw = ImageDraw.Draw(img)
|
103 |
-
current_time = self.get_current_ist()
|
104 |
-
|
105 |
if detected_weights:
|
106 |
-
# Sort by probability and area (larger text is more likely the weight)
|
107 |
detected_weights.sort(
|
108 |
-
key=lambda x: (
|
109 |
-
|
110 |
-
|
111 |
-
(x['bbox'][2][1] - x['bbox'][0][1]) # Height
|
112 |
-
),
|
113 |
reverse=True
|
114 |
)
|
115 |
-
|
116 |
best_match = detected_weights[0]
|
117 |
|
118 |
-
# Draw
|
|
|
119 |
for item in detected_weights:
|
120 |
-
bbox = item[
|
121 |
polygon = [(int(x), int(y)) for [x, y] in bbox]
|
122 |
color = "green" if item == best_match else "red"
|
123 |
draw.polygon(polygon, outline=color, width=2)
|
124 |
-
label = f"{item['weight']}g (
|
125 |
draw.text((polygon[0][0], polygon[0][1] - 15), label, fill=color)
|
126 |
|
127 |
-
# Add timestamp
|
128 |
-
draw.text((10, 10), f"
|
129 |
|
130 |
-
return
|
|
|
|
|
|
|
|
|
|
|
131 |
|
132 |
-
|
133 |
-
|
134 |
-
|
|
|
|
|
|
|
135 |
|
136 |
except Exception as e:
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
|
|
2 |
import numpy as np
|
3 |
import easyocr
|
4 |
import re
|
|
|
5 |
from PIL import Image, ImageDraw
|
6 |
import pytz
|
7 |
from datetime import datetime
|
8 |
+
from skimage import filters
|
9 |
|
10 |
class WeightDetector:
|
11 |
def __init__(self):
|
12 |
+
"""OCR optimized for 7-segment displays"""
|
13 |
self.reader = easyocr.Reader(
|
14 |
['en'],
|
15 |
gpu=True,
|
16 |
model_storage_directory='model',
|
17 |
+
download_enabled=True,
|
18 |
+
recog_network='english_g2' # Better for digital displays
|
19 |
)
|
20 |
self.ist = pytz.timezone('Asia/Kolkata')
|
21 |
+
|
22 |
def get_current_ist(self) -> str:
|
23 |
+
"""Get current IST time"""
|
24 |
+
return datetime.now(self.ist).strftime('%Y-%m-%d %H:%M:%S IST')
|
25 |
+
|
26 |
+
def is_blurry(self, image: np.ndarray, threshold=100) -> bool:
|
27 |
+
"""Check if image is blurry using Laplacian variance"""
|
28 |
+
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
29 |
+
variance = cv2.Laplacian(gray, cv2.CV_64F).var()
|
30 |
+
return variance < threshold
|
31 |
+
|
32 |
+
def preprocess_7segment(self, image: np.ndarray) -> np.ndarray:
|
33 |
+
"""Optimized preprocessing for 7-segment displays"""
|
34 |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
|
35 |
|
36 |
+
# Adaptive thresholding for digital displays
|
37 |
+
thresh = cv2.adaptiveThreshold(
|
38 |
+
gray, 255,
|
39 |
+
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
40 |
+
cv2.THRESH_BINARY_INV, 11, 2
|
41 |
+
)
|
|
|
42 |
|
43 |
+
# Remove small noise
|
44 |
+
kernel = np.ones((2, 2), np.uint8)
|
45 |
+
cleaned = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
|
46 |
|
47 |
+
return cleaned
|
48 |
+
|
49 |
+
def extract_weight(self, text: str) -> Optional[float]:
|
50 |
+
"""Extract weight value (handles decimals, units like g/kg)"""
|
51 |
+
text = text.replace(" ", "").replace(",", ".")
|
|
|
52 |
|
53 |
+
# Patterns for digital scales (e.g., "0.000g", "12.34 kg")
|
54 |
patterns = [
|
55 |
+
r'(\d+\.\d+)\s*[gGkK]', # 12.34g or 12.34kg
|
56 |
+
r'(\d+)\s*[gGkK]', # 123g or 123kg
|
57 |
+
r'(\d+\.\d+)', # Decimal only
|
58 |
+
r'(\d+)' # Whole number
|
59 |
]
|
60 |
|
61 |
for pattern in patterns:
|
|
|
63 |
if match:
|
64 |
try:
|
65 |
value = float(match.group(1))
|
66 |
+
if 'k' in text.lower(): # Convert kg to g
|
67 |
+
return value * 1000
|
|
|
68 |
return value
|
69 |
except ValueError:
|
70 |
continue
|
71 |
return None
|
72 |
+
|
73 |
+
def detect_weight(self, image_path: str) -> dict:
|
74 |
+
"""Detect weight from image with error checks"""
|
75 |
try:
|
|
|
76 |
img = Image.open(image_path).convert("RGB")
|
77 |
img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
|
78 |
|
79 |
+
# Check for blur
|
80 |
+
if self.is_blurry(img_cv):
|
81 |
+
return {
|
82 |
+
"weight": None,
|
83 |
+
"message": "⚠️ Image is blurry! Ensure clear focus.",
|
84 |
+
"image": img,
|
85 |
+
"time": self.get_current_ist()
|
86 |
+
}
|
87 |
|
88 |
+
# Preprocess for 7-segment digits
|
89 |
+
processed = self.preprocess_7segment(img_cv)
|
90 |
+
|
91 |
+
# OCR with 7-segment optimization
|
92 |
results = self.reader.readtext(
|
93 |
processed,
|
94 |
+
allowlist='0123456789.gkGKlL',
|
95 |
paragraph=False,
|
96 |
+
text_threshold=0.7,
|
97 |
+
width_ths=1.5
|
|
|
|
|
98 |
)
|
99 |
|
100 |
+
# Extract and validate weights
|
101 |
detected_weights = []
|
102 |
for (bbox, text, prob) in results:
|
103 |
+
weight = self.extract_weight(text)
|
104 |
+
if weight and prob > 0.5: # Minimum confidence
|
105 |
detected_weights.append({
|
106 |
+
"weight": weight,
|
107 |
+
"text": text,
|
108 |
+
"probability": prob,
|
109 |
+
"bbox": bbox
|
110 |
})
|
111 |
|
112 |
+
# Select best match (highest confidence + largest area)
|
|
|
|
|
|
|
113 |
if detected_weights:
|
|
|
114 |
detected_weights.sort(
|
115 |
+
key=lambda x: (x["probability"],
|
116 |
+
(x["bbox"][2][0] - x["bbox"][0][0]) * # Width
|
117 |
+
(x["bbox"][2][1] - x["bbox"][0][1])), # Height
|
|
|
|
|
118 |
reverse=True
|
119 |
)
|
|
|
120 |
best_match = detected_weights[0]
|
121 |
|
122 |
+
# Draw annotations
|
123 |
+
draw = ImageDraw.Draw(img)
|
124 |
for item in detected_weights:
|
125 |
+
bbox = item["bbox"]
|
126 |
polygon = [(int(x), int(y)) for [x, y] in bbox]
|
127 |
color = "green" if item == best_match else "red"
|
128 |
draw.polygon(polygon, outline=color, width=2)
|
129 |
+
label = f"{item['weight']}g (Conf: {item['probability']:.2f})"
|
130 |
draw.text((polygon[0][0], polygon[0][1] - 15), label, fill=color)
|
131 |
|
132 |
+
# Add timestamp
|
133 |
+
draw.text((10, 10), f"Time: {self.get_current_ist()}", fill="blue")
|
134 |
|
135 |
+
return {
|
136 |
+
"weight": best_match["weight"],
|
137 |
+
"message": f"✅ Detected: {best_match['weight']}g (Conf: {best_match['probability']:.2f})",
|
138 |
+
"image": img,
|
139 |
+
"time": self.get_current_ist()
|
140 |
+
}
|
141 |
|
142 |
+
return {
|
143 |
+
"weight": None,
|
144 |
+
"message": "❌ No weight detected. Ensure clear 7-segment digits.",
|
145 |
+
"image": img,
|
146 |
+
"time": self.get_current_ist()
|
147 |
+
}
|
148 |
|
149 |
except Exception as e:
|
150 |
+
return {
|
151 |
+
"weight": None,
|
152 |
+
"message": f"⚠️ Error: {str(e)}",
|
153 |
+
"image": None,
|
154 |
+
"time": self.get_current_ist()
|
155 |
+
}
|