Spaces:
Running
Running
Update ocr_engine.py
Browse files- ocr_engine.py +105 -239
ocr_engine.py
CHANGED
@@ -21,7 +21,7 @@ def save_debug_image(img, filename_suffix, prefix=""):
|
|
21 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
|
22 |
filename = os.path.join(DEBUG_DIR, f"{prefix}{timestamp}_{filename_suffix}.png")
|
23 |
if len(img.shape) == 3:
|
24 |
-
cv2.imwrite(filename, img)
|
25 |
else:
|
26 |
cv2.imwrite(filename, img)
|
27 |
logging.info(f"Saved debug image: {filename}")
|
@@ -32,24 +32,32 @@ def estimate_brightness(img):
|
|
32 |
return np.mean(gray)
|
33 |
|
34 |
def preprocess_image(img):
|
35 |
-
"""Preprocess image for OCR."""
|
36 |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
41 |
save_debug_image(enhanced, "02_preprocess_clahe")
|
42 |
-
|
|
|
|
|
|
|
|
|
43 |
|
44 |
def correct_rotation(img):
|
45 |
-
"""Correct image rotation."""
|
46 |
try:
|
47 |
-
|
|
|
|
|
48 |
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=50, minLineLength=30, maxLineGap=10)
|
49 |
if lines is not None:
|
50 |
angles = [np.arctan2(line[0][3] - line[0][1], line[0][2] - line[0][0]) * 180 / np.pi for line in lines]
|
51 |
angle = np.median(angles)
|
52 |
-
if abs(angle) >
|
53 |
h, w = img.shape[:2]
|
54 |
center = (w // 2, h // 2)
|
55 |
M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
@@ -62,15 +70,20 @@ def correct_rotation(img):
|
|
62 |
return img
|
63 |
|
64 |
def detect_roi(img):
|
65 |
-
"""Detect region of interest (display)."""
|
66 |
try:
|
67 |
-
save_debug_image(img, "
|
68 |
preprocessed = preprocess_image(img)
|
69 |
brightness_map = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
70 |
-
|
|
|
71 |
thresh = cv2.adaptiveThreshold(preprocessed, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
72 |
cv2.THRESH_BINARY_INV, block_size, 2)
|
73 |
-
save_debug_image(thresh, "
|
|
|
|
|
|
|
|
|
74 |
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
75 |
|
76 |
if contours:
|
@@ -81,141 +94,105 @@ def detect_roi(img):
|
|
81 |
x, y, w, h = cv2.boundingRect(c)
|
82 |
roi_brightness = np.mean(brightness_map[y:y+h, x:x+w])
|
83 |
aspect_ratio = w / h
|
84 |
-
|
85 |
-
|
86 |
-
|
|
|
87 |
logging.debug(f"Contour: Area={area}, Aspect={aspect_ratio:.2f}, Brightness={roi_brightness:.2f}")
|
88 |
|
89 |
if valid_contours:
|
90 |
contour, _ = max(valid_contours, key=lambda x: x[1])
|
91 |
x, y, w, h = cv2.boundingRect(contour)
|
92 |
-
padding
|
|
|
93 |
x, y = max(0, x - padding), max(0, y - padding)
|
94 |
w, h = min(w + 2 * padding, img.shape[1] - x), min(h + 2 * padding, img.shape[0] - y)
|
95 |
roi_img = img[y:y+h, x:x+w]
|
96 |
-
save_debug_image(roi_img, "
|
97 |
logging.info(f"Detected ROI: ({x}, {y}, {w}, {h})")
|
98 |
return roi_img, (x, y, w, h)
|
99 |
|
100 |
logging.info("No ROI found, using full image.")
|
101 |
-
save_debug_image(img, "
|
102 |
return img, None
|
103 |
except Exception as e:
|
104 |
logging.error(f"ROI detection failed: {str(e)}")
|
105 |
-
save_debug_image(img, "
|
106 |
return img, None
|
107 |
|
108 |
-
def
|
109 |
-
"""
|
110 |
-
h, w = digit_img.shape
|
111 |
-
if h < 5 or w < 3:
|
112 |
-
return None
|
113 |
-
|
114 |
-
segments = {
|
115 |
-
'top': (int(w*0.1), int(w*0.9), 0, int(h*0.25)),
|
116 |
-
'middle': (int(w*0.1), int(w*0.9), int(h*0.45), int(h*0.55)),
|
117 |
-
'bottom': (int(w*0.1), int(w*0.9), int(h*0.75), h),
|
118 |
-
'left_top': (0, int(w*0.3), int(h*0.1), int(h*0.5)),
|
119 |
-
'left_bottom': (0, int(w*0.3), int(h*0.5), int(h*0.9)),
|
120 |
-
'right_top': (int(w*0.7), w, int(h*0.1), int(h*0.5)),
|
121 |
-
'right_bottom': (int(w*0.7), w, int(h*0.5), int(h*0.9))
|
122 |
-
}
|
123 |
-
|
124 |
-
segment_presence = {}
|
125 |
-
for name, (x1, x2, y1, y2) in segments.items():
|
126 |
-
x1, y1 = max(0, x1), max(0, y1)
|
127 |
-
x2, y2 = min(w, x2), min(h, y2)
|
128 |
-
region = digit_img[y1:y2, x1:x2]
|
129 |
-
if region.size == 0:
|
130 |
-
segment_presence[name] = False
|
131 |
-
continue
|
132 |
-
pixel_count = np.sum(region == 255)
|
133 |
-
total_pixels = region.size
|
134 |
-
segment_presence[name] = pixel_count / total_pixels > (0.1 if brightness < 80 else 0.25)
|
135 |
-
|
136 |
-
digit_patterns = {
|
137 |
-
'0': ('top', 'bottom', 'left_top', 'left_bottom', 'right_top', 'right_bottom'),
|
138 |
-
'1': ('right_top', 'right_bottom'),
|
139 |
-
'2': ('top', 'middle', 'bottom', 'left_bottom', 'right_top'),
|
140 |
-
'3': ('top', 'middle', 'bottom', 'right_top', 'right_bottom'),
|
141 |
-
'4': ('middle', 'left_top', 'right_top', 'right_bottom'),
|
142 |
-
'5': ('top', 'middle', 'bottom', 'left_top', 'right_bottom'),
|
143 |
-
'6': ('top', 'middle', 'bottom', 'left_top', 'left_bottom', 'right_bottom'),
|
144 |
-
'7': ('top', 'right_top', 'right_bottom'),
|
145 |
-
'8': ('top', 'middle', 'bottom', 'left_top', 'left_bottom', 'right_top', 'right_bottom'),
|
146 |
-
'9': ('top', 'middle', 'bottom', 'left_top', 'right_top', 'right_bottom')
|
147 |
-
}
|
148 |
-
|
149 |
-
best_match = None
|
150 |
-
max_score = -1
|
151 |
-
for digit, pattern in digit_patterns.items():
|
152 |
-
matches = sum(1 for segment in pattern if segment_presence.get(segment, False))
|
153 |
-
non_matches_penalty = sum(1 for segment in segment_presence if segment not in pattern and segment_presence[segment])
|
154 |
-
score = matches - 0.1 * non_matches_penalty
|
155 |
-
if matches >= len(pattern) * 0.55:
|
156 |
-
score += 1.0
|
157 |
-
if score > max_score:
|
158 |
-
max_score = score
|
159 |
-
best_match = digit
|
160 |
-
|
161 |
-
logging.debug(f"Segment presence: {segment_presence}, Digit: {best_match}")
|
162 |
-
return best_match
|
163 |
-
|
164 |
-
def custom_seven_segment_ocr(img, roi_bbox):
|
165 |
-
"""Perform OCR for seven-segment displays."""
|
166 |
try:
|
167 |
preprocessed = preprocess_image(img)
|
168 |
brightness = estimate_brightness(img)
|
169 |
-
|
170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
171 |
results = easyocr_reader.readtext(thresh, detail=1, paragraph=False,
|
172 |
-
contrast_ths=0.
|
173 |
-
text_threshold=0.
|
174 |
-
allowlist='0123456789.', batch_size=
|
175 |
|
176 |
logging.info(f"EasyOCR results: {results}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
if not results:
|
178 |
logging.info("No digits found.")
|
179 |
-
return None
|
180 |
|
181 |
digits_info = []
|
182 |
for (bbox, text, conf) in results:
|
183 |
(x1, y1), (x2, y2), (x3, y3), (x4, y4) = bbox
|
184 |
h_bbox = max(y1, y2, y3, y4) - min(y1, y2, y3, y4)
|
185 |
-
if (text.isdigit() or text == '.') and h_bbox >
|
186 |
x_min, x_max = int(min(x1, x4)), int(max(x2, x3))
|
187 |
y_min, y_max = int(min(y1, y2)), int(max(y3, y4))
|
188 |
digits_info.append((x_min, x_max, y_min, y_max, text, conf))
|
189 |
|
|
|
|
|
|
|
|
|
190 |
digits_info.sort(key=lambda x: x[0])
|
191 |
recognized_text = ""
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
save_debug_image(digit_img_crop, f"07_digit_crop_{idx}_{easyocr_char}")
|
199 |
-
if easyocr_conf > 0.8 or easyocr_char == '.':
|
200 |
-
recognized_text += easyocr_char
|
201 |
-
else:
|
202 |
-
digit_from_segments = detect_segments(digit_img_crop, brightness)
|
203 |
-
recognized_text += digit_from_segments if digit_from_segments else easyocr_char
|
204 |
|
205 |
-
|
|
|
|
|
|
|
206 |
text = re.sub(r"[^\d\.]", "", recognized_text)
|
207 |
if text.count('.') > 1:
|
208 |
text = text.replace('.', '', text.count('.') - 1)
|
|
|
209 |
if text and re.fullmatch(r"^\d*\.?\d*$", text):
|
210 |
-
text = text.
|
211 |
-
if text == '':
|
212 |
-
|
213 |
-
return text
|
214 |
logging.info(f"Text '{recognized_text}' failed validation.")
|
215 |
-
return None
|
216 |
except Exception as e:
|
217 |
-
logging.error(f"
|
218 |
-
return None
|
219 |
|
220 |
def extract_weight_from_image(pil_img):
|
221 |
"""Extract weight from a digital scale image."""
|
@@ -225,148 +202,37 @@ def extract_weight_from_image(pil_img):
|
|
225 |
save_debug_image(img, "00_input_image")
|
226 |
img = correct_rotation(img)
|
227 |
brightness = estimate_brightness(img)
|
228 |
-
conf_threshold = 0.
|
229 |
|
230 |
roi_img, roi_bbox = detect_roi(img)
|
231 |
if roi_bbox:
|
232 |
-
conf_threshold *= 1.
|
233 |
|
234 |
-
|
235 |
-
if
|
236 |
try:
|
237 |
-
weight = float(
|
238 |
if 0.00001 <= weight <= 10000:
|
239 |
-
logging.info(f"
|
240 |
-
return
|
241 |
-
logging.warning(f"
|
242 |
except ValueError:
|
243 |
-
logging.warning(f"
|
244 |
-
|
245 |
-
logging.info("Custom OCR failed, using EasyOCR fallback.")
|
246 |
-
preprocessed_roi = preprocess_image(roi_img)
|
247 |
-
final_roi = cv2.adaptiveThreshold(preprocessed_roi, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
248 |
-
cv2.THRESH_BINARY_INV, max(9, min(31, int(roi_img.shape[0] / 25) * 2 + 1)), 2)
|
249 |
-
save_debug_image(final_roi, "08_fallback_thresh")
|
250 |
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
save_debug_image(final_roi, "08_fallback_thresh_fallback")
|
263 |
-
|
264 |
-
logging.info(f"EasyOCR results: {results}")
|
265 |
-
candidates = []
|
266 |
-
unit = None
|
267 |
-
for (bbox, text, conf) in results:
|
268 |
-
if 'kg' in text.lower():
|
269 |
-
unit = 'kg'
|
270 |
-
continue
|
271 |
-
elif 'g' in text.lower():
|
272 |
-
unit = 'g'
|
273 |
-
continue
|
274 |
-
elif 'lb' in text.lower():
|
275 |
-
unit = 'lb'
|
276 |
-
continue
|
277 |
-
text = re.sub(r"[^\d\.]", "", text)
|
278 |
-
if text.count('.') > 1:
|
279 |
-
text = text.replace('.', '', text.count('.') - 1)
|
280 |
-
text = text.strip('.')
|
281 |
-
if re.fullmatch(r"^\d*\.?\d*$", text):
|
282 |
-
try:
|
283 |
-
weight = float(text)
|
284 |
-
if unit == 'g':
|
285 |
-
weight /= 1000
|
286 |
-
elif unit == 'lb':
|
287 |
-
weight *= 0.453592
|
288 |
-
range_score = 1.5 if 0.00001 <= weight <= 10000 else 0.5
|
289 |
-
digit_count = len(text.replace('.', ''))
|
290 |
-
digit_score = 1.4 if 1 <= digit_count <= 8 else 0.6
|
291 |
-
score = conf * range_score * digit_score
|
292 |
-
if roi_bbox:
|
293 |
-
x_roi, y_roi, w_roi, h_roi = roi_bbox
|
294 |
-
roi_area = w_roi * h_roi
|
295 |
-
x_min, y_min = int(min(b[0] for b in bbox)), int(min(b[1] for b in bbox))
|
296 |
-
x_max, y_max = int(max(b[0] for b in bbox)), int(max(b[1] for b in bbox))
|
297 |
-
bbox_area = (x_max - x_min) * (y_max - y_min)
|
298 |
-
if roi_area > 0 and bbox_area / roi_area < 0.02:
|
299 |
-
score *= 0.4
|
300 |
-
candidates.append((text, conf, score, unit))
|
301 |
-
logging.info(f"Candidate: '{text}', Unit: {unit or 'none'}, Conf: {conf}, Score: {score}")
|
302 |
-
except ValueError:
|
303 |
-
logging.warning(f"Could not convert '{text}' to float.")
|
304 |
-
|
305 |
-
if not candidates and not roi_bbox:
|
306 |
-
logging.info("No candidates, trying full image.")
|
307 |
-
preprocessed_full = preprocess_image(img)
|
308 |
-
final_full = cv2.adaptiveThreshold(preprocessed_full, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
309 |
-
cv2.THRESH_BINARY_INV, max(9, min(31, int(img.shape[0] / 25) * 2 + 1)), 2)
|
310 |
-
save_debug_image(final_full, "08_fallback_full")
|
311 |
-
results = easyocr_reader.readtext(final_full, detail=1, paragraph=False,
|
312 |
-
contrast_ths=0.05, adjust_contrast=1.5,
|
313 |
-
text_threshold=0.15, mag_ratio=4.0,
|
314 |
-
allowlist='0123456789. kglb', batch_size=2, y_ths=0.3)
|
315 |
-
logging.info(f"Full image EasyOCR: {results}")
|
316 |
-
for (bbox, text, conf) in results:
|
317 |
-
if 'kg' in text.lower():
|
318 |
-
unit = 'kg'
|
319 |
-
continue
|
320 |
-
elif 'g' in text.lower():
|
321 |
-
unit = 'g'
|
322 |
-
continue
|
323 |
-
elif 'lb' in text.lower():
|
324 |
-
unit = 'lb'
|
325 |
-
continue
|
326 |
-
text = re.sub(r"[^\d\.]", "", text)
|
327 |
-
if text.count('.') > 1:
|
328 |
-
text = text.replace('.', '', text.count('.') - 1)
|
329 |
-
text = text.strip('.')
|
330 |
-
if re.fullmatch(r"^\d*\.?\d*$", text):
|
331 |
-
try:
|
332 |
-
weight = float(text)
|
333 |
-
if unit == 'g':
|
334 |
-
weight /= 1000
|
335 |
-
elif unit == 'lb':
|
336 |
-
weight *= 0.453592
|
337 |
-
range_score = 1.2 if 0.00001 <= weight <= 10000 else 0.4
|
338 |
-
digit_count = len(text.replace('.', ''))
|
339 |
-
digit_score = 1.2 if 1 <= digit_count <= 8 else 0.5
|
340 |
-
score = conf * range_score * digit_score * 0.7
|
341 |
-
candidates.append((text, conf, score, unit))
|
342 |
-
logging.info(f"Full image candidate: '{text}', Unit: {unit or 'none'}, Conf: {conf}, Score: {score}")
|
343 |
-
except ValueError:
|
344 |
-
logging.warning(f"Could not convert '{text}' to float (full image).")
|
345 |
-
|
346 |
-
if not candidates:
|
347 |
-
logging.info("No valid weight detected.")
|
348 |
-
return "Not detected", 0.0
|
349 |
-
|
350 |
-
best_weight, best_conf, best_score, best_unit = max(candidates, key=lambda x: x[2])
|
351 |
-
if "." in best_weight:
|
352 |
-
int_part, dec_part = best_weight.split(".")
|
353 |
-
int_part = int_part.lstrip("0") or "0"
|
354 |
-
dec_part = dec_part.rstrip('0')
|
355 |
-
best_weight = f"{int_part}.{dec_part}" if dec_part else int_part
|
356 |
-
else:
|
357 |
-
best_weight = best_weight.lstrip('0') or "0"
|
358 |
-
|
359 |
-
try:
|
360 |
-
final_weight = float(best_weight)
|
361 |
-
if final_weight < 0.00001 or final_weight > 10000:
|
362 |
-
best_conf *= 0.4
|
363 |
-
elif final_weight == 0 and best_conf < 0.95:
|
364 |
-
best_conf *= 0.5
|
365 |
-
except ValueError:
|
366 |
-
pass
|
367 |
|
368 |
-
logging.info(
|
369 |
-
return
|
370 |
except Exception as e:
|
371 |
logging.error(f"Weight extraction failed: {str(e)}")
|
372 |
return "Not detected", 0.0
|
|
|
21 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
|
22 |
filename = os.path.join(DEBUG_DIR, f"{prefix}{timestamp}_{filename_suffix}.png")
|
23 |
if len(img.shape) == 3:
|
24 |
+
cv2.imwrite(filename, cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
25 |
else:
|
26 |
cv2.imwrite(filename, img)
|
27 |
logging.info(f"Saved debug image: {filename}")
|
|
|
32 |
return np.mean(gray)
|
33 |
|
34 |
def preprocess_image(img):
|
35 |
+
"""Preprocess image for OCR with enhanced contrast and noise reduction."""
|
36 |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
37 |
+
# Apply Gaussian blur to reduce noise
|
38 |
+
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
39 |
+
save_debug_image(blurred, "01_preprocess_blur")
|
40 |
+
# Use adaptive histogram equalization for better contrast
|
41 |
+
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8, 8))
|
42 |
+
enhanced = clahe.apply(blurred)
|
43 |
save_debug_image(enhanced, "02_preprocess_clahe")
|
44 |
+
# Morphological operations to enhance digits
|
45 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
|
46 |
+
morphed = cv2.morphologyEx(enhanced, cv2.MORPH_CLOSE, kernel)
|
47 |
+
save_debug_image(morphed, "03_preprocess_morph")
|
48 |
+
return morphed
|
49 |
|
50 |
def correct_rotation(img):
|
51 |
+
"""Correct image rotation using edge detection."""
|
52 |
try:
|
53 |
+
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
54 |
+
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
55 |
+
edges = cv2.Canny(blurred, 50, 150)
|
56 |
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=50, minLineLength=30, maxLineGap=10)
|
57 |
if lines is not None:
|
58 |
angles = [np.arctan2(line[0][3] - line[0][1], line[0][2] - line[0][0]) * 180 / np.pi for line in lines]
|
59 |
angle = np.median(angles)
|
60 |
+
if abs(angle) > 1.5:
|
61 |
h, w = img.shape[:2]
|
62 |
center = (w // 2, h // 2)
|
63 |
M = cv2.getRotationMatrix2D(center, angle, 1.0)
|
|
|
70 |
return img
|
71 |
|
72 |
def detect_roi(img):
|
73 |
+
"""Detect region of interest (display) with refined contour filtering."""
|
74 |
try:
|
75 |
+
save_debug_image(img, "04_original")
|
76 |
preprocessed = preprocess_image(img)
|
77 |
brightness_map = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
78 |
+
# Dynamic block size based on image dimensions
|
79 |
+
block_size = max(11, min(31, int(img.shape[0] / 20) * 2 + 1))
|
80 |
thresh = cv2.adaptiveThreshold(preprocessed, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
81 |
cv2.THRESH_BINARY_INV, block_size, 2)
|
82 |
+
save_debug_image(thresh, "05_roi_threshold")
|
83 |
+
# Morphological operations to connect digit segments
|
84 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
|
85 |
+
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
|
86 |
+
save_debug_image(thresh, "06_roi_morph")
|
87 |
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
88 |
|
89 |
if contours:
|
|
|
94 |
x, y, w, h = cv2.boundingRect(c)
|
95 |
roi_brightness = np.mean(brightness_map[y:y+h, x:x+w])
|
96 |
aspect_ratio = w / h
|
97 |
+
# Relaxed constraints for ROI detection
|
98 |
+
if (100 < area < (img_area * 0.9) and
|
99 |
+
0.3 <= aspect_ratio <= 20.0 and w > 40 and h > 15 and roi_brightness > 20):
|
100 |
+
valid_contours.append((c, area * roi_brightness))
|
101 |
logging.debug(f"Contour: Area={area}, Aspect={aspect_ratio:.2f}, Brightness={roi_brightness:.2f}")
|
102 |
|
103 |
if valid_contours:
|
104 |
contour, _ = max(valid_contours, key=lambda x: x[1])
|
105 |
x, y, w, h = cv2.boundingRect(contour)
|
106 |
+
# Dynamic padding based on ROI size
|
107 |
+
padding = max(10, min(50, int(min(w, h) * 0.2)))
|
108 |
x, y = max(0, x - padding), max(0, y - padding)
|
109 |
w, h = min(w + 2 * padding, img.shape[1] - x), min(h + 2 * padding, img.shape[0] - y)
|
110 |
roi_img = img[y:y+h, x:x+w]
|
111 |
+
save_debug_image(roi_img, "07_detected_roi")
|
112 |
logging.info(f"Detected ROI: ({x}, {y}, {w}, {h})")
|
113 |
return roi_img, (x, y, w, h)
|
114 |
|
115 |
logging.info("No ROI found, using full image.")
|
116 |
+
save_debug_image(img, "07_no_roi_fallback")
|
117 |
return img, None
|
118 |
except Exception as e:
|
119 |
logging.error(f"ROI detection failed: {str(e)}")
|
120 |
+
save_debug_image(img, "07_roi_error_fallback")
|
121 |
return img, None
|
122 |
|
123 |
+
def perform_ocr(img, roi_bbox):
|
124 |
+
"""Perform OCR optimized for digital displays."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
125 |
try:
|
126 |
preprocessed = preprocess_image(img)
|
127 |
brightness = estimate_brightness(img)
|
128 |
+
# Dynamic thresholding based on brightness
|
129 |
+
thresh_value = 0 if brightness < 50 else (127 if brightness < 100 else 200)
|
130 |
+
_, thresh = cv2.threshold(preprocessed, thresh_value, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
131 |
+
save_debug_image(thresh, "08_ocr_threshold")
|
132 |
+
# Morphological operations to clean up digits
|
133 |
+
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
|
134 |
+
thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
|
135 |
+
save_debug_image(thresh, "09_ocr_morph")
|
136 |
+
|
137 |
+
# Optimized EasyOCR parameters for seven-segment displays
|
138 |
results = easyocr_reader.readtext(thresh, detail=1, paragraph=False,
|
139 |
+
contrast_ths=0.1, adjust_contrast=1.5,
|
140 |
+
text_threshold=0.2, mag_ratio=3.0,
|
141 |
+
allowlist='0123456789.', batch_size=1, y_ths=0.2)
|
142 |
|
143 |
logging.info(f"EasyOCR results: {results}")
|
144 |
+
if not results:
|
145 |
+
logging.info("No text detected, trying fallback parameters.")
|
146 |
+
results = easyocr_reader.readtext(thresh, detail=1, paragraph=False,
|
147 |
+
contrast_ths=0.05, adjust_contrast=2.0,
|
148 |
+
text_threshold=0.1, mag_ratio=4.0,
|
149 |
+
allowlist='0123456789.', batch_size=1, y_ths=0.2)
|
150 |
+
save_debug_image(thresh, "09_fallback_threshold")
|
151 |
+
|
152 |
if not results:
|
153 |
logging.info("No digits found.")
|
154 |
+
return None, 0.0
|
155 |
|
156 |
digits_info = []
|
157 |
for (bbox, text, conf) in results:
|
158 |
(x1, y1), (x2, y2), (x3, y3), (x4, y4) = bbox
|
159 |
h_bbox = max(y1, y2, y3, y4) - min(y1, y2, y3, y4)
|
160 |
+
if (text.isdigit() or text == '.') and h_bbox > 5 and conf > 0.1:
|
161 |
x_min, x_max = int(min(x1, x4)), int(max(x2, x3))
|
162 |
y_min, y_max = int(min(y1, y2)), int(max(y3, y4))
|
163 |
digits_info.append((x_min, x_max, y_min, y_max, text, conf))
|
164 |
|
165 |
+
if not digits_info:
|
166 |
+
logging.info("No valid digits after filtering.")
|
167 |
+
return None, 0.0
|
168 |
+
|
169 |
digits_info.sort(key=lambda x: x[0])
|
170 |
recognized_text = ""
|
171 |
+
total_conf = 0.0
|
172 |
+
conf_count = 0
|
173 |
+
for _, _, _, _, char, conf in digits_info:
|
174 |
+
recognized_text += char
|
175 |
+
total_conf += conf
|
176 |
+
conf_count += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
|
178 |
+
avg_conf = total_conf / conf_count if conf_count > 0 else 0.0
|
179 |
+
logging.info(f"Recognized text: {recognized_text}, Average confidence: {avg_conf:.2f}")
|
180 |
+
|
181 |
+
# Validate and clean the recognized text
|
182 |
text = re.sub(r"[^\d\.]", "", recognized_text)
|
183 |
if text.count('.') > 1:
|
184 |
text = text.replace('.', '', text.count('.') - 1)
|
185 |
+
text = text.strip('.')
|
186 |
if text and re.fullmatch(r"^\d*\.?\d*$", text):
|
187 |
+
text = text.lstrip('0') or '0'
|
188 |
+
if text == '0' and avg_conf < 0.9:
|
189 |
+
avg_conf *= 0.7
|
190 |
+
return text, avg_conf * 100
|
191 |
logging.info(f"Text '{recognized_text}' failed validation.")
|
192 |
+
return None, 0.0
|
193 |
except Exception as e:
|
194 |
+
logging.error(f"OCR failed: {str(e)}")
|
195 |
+
return None, 0.0
|
196 |
|
197 |
def extract_weight_from_image(pil_img):
|
198 |
"""Extract weight from a digital scale image."""
|
|
|
202 |
save_debug_image(img, "00_input_image")
|
203 |
img = correct_rotation(img)
|
204 |
brightness = estimate_brightness(img)
|
205 |
+
conf_threshold = 0.5 if brightness > 120 else (0.3 if brightness > 60 else 0.2)
|
206 |
|
207 |
roi_img, roi_bbox = detect_roi(img)
|
208 |
if roi_bbox:
|
209 |
+
conf_threshold *= 1.1 if (roi_bbox[2] * roi_bbox[3]) > (img.shape[0] * img.shape[1] * 0.4) else 1.0
|
210 |
|
211 |
+
result, confidence = perform_ocr(roi_img, roi_bbox)
|
212 |
+
if result and confidence >= conf_threshold * 100:
|
213 |
try:
|
214 |
+
weight = float(result)
|
215 |
if 0.00001 <= weight <= 10000:
|
216 |
+
logging.info(f"Detected weight: {result} kg, Confidence: {confidence:.2f}%")
|
217 |
+
return result, confidence
|
218 |
+
logging.warning(f"Weight {result} out of range.")
|
219 |
except ValueError:
|
220 |
+
logging.warning(f"Invalid weight format: {result}")
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
|
222 |
+
logging.info("Primary OCR failed, using full image fallback.")
|
223 |
+
result, confidence = perform_ocr(img, None)
|
224 |
+
if result and confidence >= conf_threshold * 0.8 * 100:
|
225 |
+
try:
|
226 |
+
weight = float(result)
|
227 |
+
if 0.00001 <= weight <= 10000:
|
228 |
+
logging.info(f"Full image weight: {result} kg, Confidence: {confidence:.2f}%")
|
229 |
+
return result, confidence
|
230 |
+
logging.warning(f"Full image weight {result} out of range.")
|
231 |
+
except ValueError:
|
232 |
+
logging.warning(f"Invalid full image weight format: {result}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
|
234 |
+
logging.info("No valid weight detected.")
|
235 |
+
return "Not detected", 0.0
|
236 |
except Exception as e:
|
237 |
logging.error(f"Weight extraction failed: {str(e)}")
|
238 |
return "Not detected", 0.0
|