Spaces:
Sleeping
Sleeping
Update ocr_engine.py
Browse files- ocr_engine.py +105 -143
ocr_engine.py
CHANGED
|
@@ -27,73 +27,85 @@ def save_debug_image(img, filename_suffix, prefix=""):
|
|
| 27 |
logging.info(f"Saved debug image: {filename}")
|
| 28 |
|
| 29 |
def estimate_brightness(img):
|
| 30 |
-
"""Estimate image brightness to detect illuminated displays"""
|
| 31 |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 32 |
return np.mean(gray)
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
def detect_roi(img):
|
| 35 |
-
"""Detect and crop the region of interest (likely the digital display)"""
|
| 36 |
try:
|
| 37 |
-
save_debug_image(img, "
|
| 38 |
-
|
| 39 |
-
save_debug_image(gray, "02_grayscale")
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
thresh = cv2.adaptiveThreshold(
|
| 43 |
-
cv2.
|
| 44 |
-
save_debug_image(thresh, "
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
| 49 |
|
| 50 |
-
contours, _ = cv2.findContours(
|
| 51 |
|
| 52 |
if contours:
|
| 53 |
img_area = img.shape[0] * img.shape[1]
|
| 54 |
valid_contours = []
|
| 55 |
for c in contours:
|
| 56 |
area = cv2.contourArea(c)
|
| 57 |
-
|
| 58 |
-
if 500 < area < (img_area * 0.95):
|
| 59 |
x, y, w, h = cv2.boundingRect(c)
|
| 60 |
aspect_ratio = w / h
|
| 61 |
-
if 1.
|
| 62 |
valid_contours.append(c)
|
| 63 |
-
|
| 64 |
if valid_contours:
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
logging.info("No suitable ROI found, returning original image.")
|
| 76 |
-
save_debug_image(img, "
|
| 77 |
return img, None
|
| 78 |
except Exception as e:
|
| 79 |
logging.error(f"ROI detection failed: {str(e)}")
|
| 80 |
-
save_debug_image(img, "
|
| 81 |
return img, None
|
| 82 |
|
| 83 |
def detect_segments(digit_img):
|
| 84 |
-
"""Detect seven-segment patterns in a digit image"""
|
| 85 |
h, w = digit_img.shape
|
| 86 |
-
if h <
|
| 87 |
return None
|
| 88 |
|
| 89 |
segments = {
|
| 90 |
-
'top': (int(w*0.
|
| 91 |
-
'middle': (int(w*0.
|
| 92 |
-
'bottom': (int(w*0.
|
| 93 |
-
'left_top': (0, int(w*0.
|
| 94 |
-
'left_bottom': (0, int(w*0.
|
| 95 |
-
'right_top': (int(w*0.
|
| 96 |
-
'right_bottom': (int(w*0.
|
| 97 |
}
|
| 98 |
|
| 99 |
segment_presence = {}
|
|
@@ -106,7 +118,7 @@ def detect_segments(digit_img):
|
|
| 106 |
continue
|
| 107 |
pixel_count = np.sum(region == 255)
|
| 108 |
total_pixels = region.size
|
| 109 |
-
segment_presence[name] = pixel_count / total_pixels > 0.
|
| 110 |
|
| 111 |
digit_patterns = {
|
| 112 |
'0': ('top', 'bottom', 'left_top', 'left_bottom', 'right_top', 'right_bottom'),
|
|
@@ -126,37 +138,34 @@ def detect_segments(digit_img):
|
|
| 126 |
for digit, pattern in digit_patterns.items():
|
| 127 |
matches = sum(1 for segment in pattern if segment_presence.get(segment, False))
|
| 128 |
non_matches_penalty = sum(1 for segment in segment_presence if segment not in pattern and segment_presence[segment])
|
| 129 |
-
|
| 130 |
if all(segment_presence.get(s, False) for s in pattern):
|
| 131 |
-
|
| 132 |
-
if
|
| 133 |
-
max_score =
|
| 134 |
best_match = digit
|
| 135 |
-
elif current_score == max_score and best_match is not None:
|
| 136 |
-
current_digit_non_matches = sum(1 for segment in segment_presence if segment not in pattern and segment_presence[segment])
|
| 137 |
-
best_digit_pattern = digit_patterns[best_match]
|
| 138 |
-
best_digit_non_matches = sum(1 for segment in segment_presence if segment not in best_digit_pattern and segment_presence[segment])
|
| 139 |
-
if current_digit_non_matches < best_digit_non_matches:
|
| 140 |
-
best_match = digit
|
| 141 |
|
| 142 |
logging.debug(f"Segment presence: {segment_presence}, Detected digit: {best_match}")
|
| 143 |
return best_match
|
| 144 |
|
| 145 |
def custom_seven_segment_ocr(img, roi_bbox):
|
| 146 |
-
"""Perform custom OCR for seven-segment displays"""
|
| 147 |
try:
|
| 148 |
-
|
| 149 |
brightness = estimate_brightness(img)
|
| 150 |
-
if brightness
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
results = easyocr_reader.readtext(thresh, detail=1, paragraph=False,
|
| 157 |
-
contrast_ths=0.
|
| 158 |
-
text_threshold=0.
|
| 159 |
-
allowlist='0123456789.', y_ths=0.
|
| 160 |
|
| 161 |
logging.info(f"EasyOCR results: {results}")
|
| 162 |
if not results:
|
|
@@ -167,7 +176,7 @@ def custom_seven_segment_ocr(img, roi_bbox):
|
|
| 167 |
for (bbox, text, conf) in results:
|
| 168 |
(x1, y1), (x2, y2), (x3, y3), (x4, y4) = bbox
|
| 169 |
h_bbox = max(y1, y2, y3, y4) - min(y1, y2, y3, y4)
|
| 170 |
-
if len(text) == 1 and (text.isdigit() or text == '.') and h_bbox >
|
| 171 |
x_min, x_max = int(min(x1, x4)), int(max(x2, x3))
|
| 172 |
y_min, y_max = int(min(y1, y2)), int(max(y3, y4))
|
| 173 |
digits_info.append((x_min, x_max, y_min, y_max, text, conf))
|
|
@@ -180,21 +189,18 @@ def custom_seven_segment_ocr(img, roi_bbox):
|
|
| 180 |
if x_max <= x_min or y_max <= y_min:
|
| 181 |
continue
|
| 182 |
digit_img_crop = thresh[y_min:y_max, x_min:x_max]
|
| 183 |
-
save_debug_image(digit_img_crop, f"
|
| 184 |
-
if easyocr_conf > 0.
|
| 185 |
recognized_text += easyocr_char
|
| 186 |
else:
|
| 187 |
digit_from_segments = detect_segments(digit_img_crop)
|
| 188 |
-
if digit_from_segments
|
| 189 |
-
recognized_text += digit_from_segments
|
| 190 |
-
else:
|
| 191 |
-
recognized_text += easyocr_char
|
| 192 |
|
| 193 |
logging.info(f"Before validation, recognized_text: {recognized_text}")
|
| 194 |
text = re.sub(r"[^\d\.]", "", recognized_text)
|
| 195 |
if text.count('.') > 1:
|
| 196 |
text = text.replace('.', '', text.count('.') - 1)
|
| 197 |
-
if text and re.fullmatch(r"^\d*\.?\d
|
| 198 |
if text.startswith('.'):
|
| 199 |
text = "0" + text
|
| 200 |
if text.endswith('.'):
|
|
@@ -209,92 +215,56 @@ def custom_seven_segment_ocr(img, roi_bbox):
|
|
| 209 |
return None
|
| 210 |
|
| 211 |
def extract_weight_from_image(pil_img):
|
| 212 |
-
"""Extract weight from a PIL image of a digital scale display"""
|
| 213 |
try:
|
| 214 |
img = np.array(pil_img)
|
| 215 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
| 216 |
-
save_debug_image(img, "00_input_image")
|
| 217 |
|
| 218 |
brightness = estimate_brightness(img)
|
| 219 |
-
conf_threshold = 0.
|
| 220 |
|
| 221 |
roi_img, roi_bbox = detect_roi(img)
|
| 222 |
custom_result = custom_seven_segment_ocr(roi_img, roi_bbox)
|
| 223 |
if custom_result:
|
| 224 |
-
if "." in custom_result:
|
| 225 |
-
int_part, dec_part = custom_result.split(".")
|
| 226 |
-
int_part = int_part.lstrip("0") or "0"
|
| 227 |
-
dec_part = dec_part.rstrip('0')
|
| 228 |
-
if not dec_part and int_part != "0":
|
| 229 |
-
custom_result = int_part
|
| 230 |
-
elif not dec_part and int_part == "0":
|
| 231 |
-
custom_result = "0"
|
| 232 |
-
else:
|
| 233 |
-
custom_result = f"{int_part}.{dec_part}"
|
| 234 |
-
else:
|
| 235 |
-
custom_result = custom_result.lstrip('0') or "0"
|
| 236 |
try:
|
| 237 |
-
float(custom_result)
|
| 238 |
-
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
| 240 |
except ValueError:
|
| 241 |
-
logging.warning(f"Custom OCR result '{custom_result}' is not a valid number
|
| 242 |
-
custom_result = None
|
| 243 |
|
| 244 |
-
logging.info("Custom OCR failed or invalid, falling back to
|
| 245 |
-
|
| 246 |
-
kernel_sharpening = np.array([[-1
|
| 247 |
-
sharpened_roi = cv2.filter2D(
|
| 248 |
-
save_debug_image(sharpened_roi, "
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
save_debug_image(
|
| 252 |
|
| 253 |
-
results = easyocr_reader.readtext(
|
| 254 |
-
contrast_ths=0.
|
| 255 |
-
text_threshold=0.5, mag_ratio=
|
| 256 |
-
allowlist='0123456789.', batch_size=4, y_ths=0.
|
| 257 |
|
| 258 |
best_weight = None
|
| 259 |
best_conf = 0.0
|
| 260 |
best_score = 0.0
|
| 261 |
for (bbox, text, conf) in results:
|
| 262 |
-
text = text.lower().strip()
|
| 263 |
-
text = text.replace(",", ".").replace(";", ".").replace(":", ".").replace(" ", "")
|
| 264 |
-
text = text.replace("o", "0").replace("O", "0").replace("q", "0").replace("Q", "0")
|
| 265 |
-
text = text.replace("s", "5").replace("S", "5")
|
| 266 |
-
text = text.replace("g", "9").replace("G", "6")
|
| 267 |
-
text = text.replace("l", "1").replace("I", "1").replace("|", "1")
|
| 268 |
-
text = text.replace("b", "8").replace("B", "8")
|
| 269 |
-
text = text.replace("z", "2").replace("Z", "2")
|
| 270 |
-
text = text.replace("a", "4").replace("A", "4")
|
| 271 |
-
text = text.replace("e", "3")
|
| 272 |
-
text = text.replace("t", "7")
|
| 273 |
-
text = text.replace("~", "").replace("`", "")
|
| 274 |
-
text = re.sub(r"(kgs|kg|k|lb|g|gr|pounds|lbs)\b", "", text)
|
| 275 |
text = re.sub(r"[^\d\.]", "", text)
|
| 276 |
if text.count('.') > 1:
|
| 277 |
-
|
| 278 |
-
text = parts[0] + '.' + ''.join(parts[1:])
|
| 279 |
text = text.strip('.')
|
| 280 |
-
if re.fullmatch(r"^\d*\.?\d
|
| 281 |
try:
|
| 282 |
weight = float(text)
|
| 283 |
-
range_score = 1.0
|
| 284 |
-
if 0.1 <= weight <= 250:
|
| 285 |
-
range_score = 1.5
|
| 286 |
-
elif weight > 250 and weight <= 500:
|
| 287 |
-
range_score = 1.2
|
| 288 |
-
elif weight > 500 and weight <= 1000:
|
| 289 |
-
range_score = 1.0
|
| 290 |
-
else:
|
| 291 |
-
range_score = 0.5
|
| 292 |
digit_count = len(text.replace('.', ''))
|
| 293 |
-
digit_score = 1.0
|
| 294 |
-
if digit_count >= 2 and digit_count <= 5:
|
| 295 |
-
digit_score = 1.3
|
| 296 |
-
elif digit_count == 1:
|
| 297 |
-
digit_score = 0.8
|
| 298 |
score = conf * range_score * digit_score
|
| 299 |
if roi_bbox:
|
| 300 |
(x_roi, y_roi, w_roi, h_roi) = roi_bbox
|
|
@@ -302,11 +272,8 @@ def extract_weight_from_image(pil_img):
|
|
| 302 |
x_min, y_min = int(min(b[0] for b in bbox)), int(min(b[1] for b in bbox))
|
| 303 |
x_max, y_max = int(max(b[0] for b in bbox)), int(max(b[1] for b in bbox))
|
| 304 |
bbox_area = (x_max - x_min) * (y_max - y_min)
|
| 305 |
-
if roi_area > 0 and bbox_area / roi_area < 0.
|
| 306 |
-
score *= 0.
|
| 307 |
-
bbox_aspect_ratio = (x_max - x_min) / (y_max - y_min) if (y_max - y_min) > 0 else 0
|
| 308 |
-
if bbox_aspect_ratio < 0.2:
|
| 309 |
-
score *= 0.7
|
| 310 |
if score > best_score and conf > conf_threshold:
|
| 311 |
best_weight = text
|
| 312 |
best_conf = conf
|
|
@@ -320,24 +287,19 @@ def extract_weight_from_image(pil_img):
|
|
| 320 |
logging.info("No valid weight detected after all attempts.")
|
| 321 |
return "Not detected", 0.0
|
| 322 |
|
|
|
|
| 323 |
if "." in best_weight:
|
| 324 |
int_part, dec_part = best_weight.split(".")
|
| 325 |
int_part = int_part.lstrip("0") or "0"
|
| 326 |
dec_part = dec_part.rstrip('0')
|
| 327 |
-
|
| 328 |
-
best_weight = int_part
|
| 329 |
-
elif not dec_part and int_part == "0":
|
| 330 |
-
best_weight = "0"
|
| 331 |
-
else:
|
| 332 |
-
best_weight = f"{int_part}.{dec_part}"
|
| 333 |
else:
|
| 334 |
best_weight = best_weight.lstrip('0') or "0"
|
| 335 |
|
| 336 |
try:
|
| 337 |
-
|
| 338 |
-
if
|
| 339 |
-
|
| 340 |
-
best_conf *= 0.5
|
| 341 |
except ValueError:
|
| 342 |
pass
|
| 343 |
|
|
|
|
| 27 |
logging.info(f"Saved debug image: {filename}")
|
| 28 |
|
| 29 |
def estimate_brightness(img):
|
| 30 |
+
"""Estimate image brightness to detect illuminated displays."""
|
| 31 |
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
|
| 32 |
return np.mean(gray)
|
| 33 |
|
| 34 |
+
def preprocess_image(img):
|
| 35 |
+
"""Preprocess image for better OCR accuracy."""
|
| 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_blurred")
|
| 40 |
+
# Enhance contrast using CLAHE
|
| 41 |
+
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
| 42 |
+
enhanced = clahe.apply(blurred)
|
| 43 |
+
save_debug_image(enhanced, "02_preprocess_clahe")
|
| 44 |
+
return enhanced
|
| 45 |
+
|
| 46 |
def detect_roi(img):
|
| 47 |
+
"""Detect and crop the region of interest (likely the digital display)."""
|
| 48 |
try:
|
| 49 |
+
save_debug_image(img, "03_original")
|
| 50 |
+
preprocessed = preprocess_image(img)
|
|
|
|
| 51 |
|
| 52 |
+
# Adaptive thresholding with refined parameters
|
| 53 |
+
thresh = cv2.adaptiveThreshold(preprocessed, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
| 54 |
+
cv2.THRESH_BINARY_INV, 15, 5)
|
| 55 |
+
save_debug_image(thresh, "04_roi_adaptive_threshold")
|
| 56 |
|
| 57 |
+
# Morphological operations to connect digits
|
| 58 |
+
kernel = np.ones((5, 5), np.uint8)
|
| 59 |
+
dilated = cv2.dilate(thresh, kernel, iterations=2)
|
| 60 |
+
eroded = cv2.erode(dilated, kernel, iterations=1)
|
| 61 |
+
save_debug_image(eroded, "05_roi_morphological")
|
| 62 |
|
| 63 |
+
contours, _ = cv2.findContours(eroded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 64 |
|
| 65 |
if contours:
|
| 66 |
img_area = img.shape[0] * img.shape[1]
|
| 67 |
valid_contours = []
|
| 68 |
for c in contours:
|
| 69 |
area = cv2.contourArea(c)
|
| 70 |
+
if 1000 < area < (img_area * 0.9):
|
|
|
|
| 71 |
x, y, w, h = cv2.boundingRect(c)
|
| 72 |
aspect_ratio = w / h
|
| 73 |
+
if 1.8 <= aspect_ratio <= 8.0 and w > 100 and h > 50:
|
| 74 |
valid_contours.append(c)
|
| 75 |
+
|
| 76 |
if valid_contours:
|
| 77 |
+
contour = max(valid_contours, key=cv2.contourArea)
|
| 78 |
+
x, y, w, h = cv2.boundingRect(contour)
|
| 79 |
+
padding = 80
|
| 80 |
+
x, y = max(0, x - padding), max(0, y - padding)
|
| 81 |
+
w, h = min(w + 2 * padding, img.shape[1] - x), min(h + 2 * padding, img.shape[0] - y)
|
| 82 |
+
roi_img = img[y:y+h, x:x+w]
|
| 83 |
+
save_debug_image(roi_img, "06_detected_roi")
|
| 84 |
+
logging.info(f"Detected ROI with dimensions: ({x}, {y}, {w}, {h})")
|
| 85 |
+
return roi_img, (x, y, w, h)
|
| 86 |
|
| 87 |
logging.info("No suitable ROI found, returning original image.")
|
| 88 |
+
save_debug_image(img, "06_no_roi_original_fallback")
|
| 89 |
return img, None
|
| 90 |
except Exception as e:
|
| 91 |
logging.error(f"ROI detection failed: {str(e)}")
|
| 92 |
+
save_debug_image(img, "06_roi_detection_error_fallback")
|
| 93 |
return img, None
|
| 94 |
|
| 95 |
def detect_segments(digit_img):
|
| 96 |
+
"""Detect seven-segment patterns in a digit image."""
|
| 97 |
h, w = digit_img.shape
|
| 98 |
+
if h < 20 or w < 15:
|
| 99 |
return None
|
| 100 |
|
| 101 |
segments = {
|
| 102 |
+
'top': (int(w*0.1), int(w*0.9), 0, int(h*0.15)),
|
| 103 |
+
'middle': (int(w*0.1), int(w*0.9), int(h*0.45), int(h*0.55)),
|
| 104 |
+
'bottom': (int(w*0.1), int(w*0.9), int(h*0.85), h),
|
| 105 |
+
'left_top': (0, int(w*0.2), int(h*0.1), int(h*0.5)),
|
| 106 |
+
'left_bottom': (0, int(w*0.2), int(h*0.5), int(h*0.9)),
|
| 107 |
+
'right_top': (int(w*0.8), w, int(h*0.1), int(h*0.5)),
|
| 108 |
+
'right_bottom': (int(w*0.8), w, int(h*0.5), int(h*0.9))
|
| 109 |
}
|
| 110 |
|
| 111 |
segment_presence = {}
|
|
|
|
| 118 |
continue
|
| 119 |
pixel_count = np.sum(region == 255)
|
| 120 |
total_pixels = region.size
|
| 121 |
+
segment_presence[name] = pixel_count / total_pixels > 0.4
|
| 122 |
|
| 123 |
digit_patterns = {
|
| 124 |
'0': ('top', 'bottom', 'left_top', 'left_bottom', 'right_top', 'right_bottom'),
|
|
|
|
| 138 |
for digit, pattern in digit_patterns.items():
|
| 139 |
matches = sum(1 for segment in pattern if segment_presence.get(segment, False))
|
| 140 |
non_matches_penalty = sum(1 for segment in segment_presence if segment not in pattern and segment_presence[segment])
|
| 141 |
+
score = matches - 0.5 * non_matches_penalty
|
| 142 |
if all(segment_presence.get(s, False) for s in pattern):
|
| 143 |
+
score += 1.0
|
| 144 |
+
if score > max_score:
|
| 145 |
+
max_score = score
|
| 146 |
best_match = digit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
logging.debug(f"Segment presence: {segment_presence}, Detected digit: {best_match}")
|
| 149 |
return best_match
|
| 150 |
|
| 151 |
def custom_seven_segment_ocr(img, roi_bbox):
|
| 152 |
+
"""Perform custom OCR for seven-segment displays."""
|
| 153 |
try:
|
| 154 |
+
preprocessed = preprocess_image(img)
|
| 155 |
brightness = estimate_brightness(img)
|
| 156 |
+
thresh_value = 100 if brightness < 100 else 0
|
| 157 |
+
_, thresh = cv2.threshold(preprocessed, thresh_value, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
|
| 158 |
+
save_debug_image(thresh, "07_roi_thresh_for_digits")
|
| 159 |
+
|
| 160 |
+
# Morphological operations to enhance digit segments
|
| 161 |
+
kernel = np.ones((3, 3), np.uint8)
|
| 162 |
+
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel, iterations=2)
|
| 163 |
+
save_debug_image(thresh, "08_morph_closed")
|
| 164 |
|
| 165 |
results = easyocr_reader.readtext(thresh, detail=1, paragraph=False,
|
| 166 |
+
contrast_ths=0.3, adjust_contrast=1.0,
|
| 167 |
+
text_threshold=0.6, mag_ratio=3.0,
|
| 168 |
+
allowlist='0123456789.', y_ths=0.2)
|
| 169 |
|
| 170 |
logging.info(f"EasyOCR results: {results}")
|
| 171 |
if not results:
|
|
|
|
| 176 |
for (bbox, text, conf) in results:
|
| 177 |
(x1, y1), (x2, y2), (x3, y3), (x4, y4) = bbox
|
| 178 |
h_bbox = max(y1, y2, y3, y4) - min(y1, y2, y3, y4)
|
| 179 |
+
if len(text) == 1 and (text.isdigit() or text == '.') and h_bbox > 10:
|
| 180 |
x_min, x_max = int(min(x1, x4)), int(max(x2, x3))
|
| 181 |
y_min, y_max = int(min(y1, y2)), int(max(y3, y4))
|
| 182 |
digits_info.append((x_min, x_max, y_min, y_max, text, conf))
|
|
|
|
| 189 |
if x_max <= x_min or y_max <= y_min:
|
| 190 |
continue
|
| 191 |
digit_img_crop = thresh[y_min:y_max, x_min:x_max]
|
| 192 |
+
save_debug_image(digit_img_crop, f"09_digit_crop_{idx}_{easyocr_char}")
|
| 193 |
+
if easyocr_conf > 0.95 or easyocr_char == '.':
|
| 194 |
recognized_text += easyocr_char
|
| 195 |
else:
|
| 196 |
digit_from_segments = detect_segments(digit_img_crop)
|
| 197 |
+
recognized_text += digit_from_segments if digit_from_segments else easyocr_char
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
logging.info(f"Before validation, recognized_text: {recognized_text}")
|
| 200 |
text = re.sub(r"[^\d\.]", "", recognized_text)
|
| 201 |
if text.count('.') > 1:
|
| 202 |
text = text.replace('.', '', text.count('.') - 1)
|
| 203 |
+
if text and re.fullmatch(r"^\d*\.?\d+$", text):
|
| 204 |
if text.startswith('.'):
|
| 205 |
text = "0" + text
|
| 206 |
if text.endswith('.'):
|
|
|
|
| 215 |
return None
|
| 216 |
|
| 217 |
def extract_weight_from_image(pil_img):
|
| 218 |
+
"""Extract weight from a PIL image of a digital scale display."""
|
| 219 |
try:
|
| 220 |
img = np.array(pil_img)
|
| 221 |
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
|
| 222 |
+
save_debug_image(img, "00_input_image")
|
| 223 |
|
| 224 |
brightness = estimate_brightness(img)
|
| 225 |
+
conf_threshold = 0.7 if brightness > 150 else (0.6 if brightness > 80 else 0.5)
|
| 226 |
|
| 227 |
roi_img, roi_bbox = detect_roi(img)
|
| 228 |
custom_result = custom_seven_segment_ocr(roi_img, roi_bbox)
|
| 229 |
if custom_result:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
try:
|
| 231 |
+
weight = float(custom_result)
|
| 232 |
+
if 0.1 <= weight <= 300:
|
| 233 |
+
logging.info(f"Custom OCR result: {custom_result}, Confidence: 95.0%")
|
| 234 |
+
return custom_result, 95.0
|
| 235 |
+
else:
|
| 236 |
+
logging.warning(f"Custom OCR result {custom_result} outside typical weight range.")
|
| 237 |
except ValueError:
|
| 238 |
+
logging.warning(f"Custom OCR result '{custom_result}' is not a valid number.")
|
|
|
|
| 239 |
|
| 240 |
+
logging.info("Custom OCR failed or invalid, falling back to enhanced EasyOCR.")
|
| 241 |
+
preprocessed_roi = preprocess_image(roi_img)
|
| 242 |
+
kernel_sharpening = np.array([[-1, -1, -1], [-1, 9, -1], [-1, -1, -1]])
|
| 243 |
+
sharpened_roi = cv2.filter2D(preprocessed_roi, -1, kernel_sharpening)
|
| 244 |
+
save_debug_image(sharpened_roi, "10_fallback_sharpened")
|
| 245 |
+
final_roi = cv2.adaptiveThreshold(sharpened_roi, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
|
| 246 |
+
cv2.THRESH_BINARY_INV, 25, 8)
|
| 247 |
+
save_debug_image(final_roi, "11_fallback_adaptive_thresh")
|
| 248 |
|
| 249 |
+
results = easyocr_reader.readtext(final_roi, detail=1, paragraph=False,
|
| 250 |
+
contrast_ths=0.4, adjust_contrast=1.2,
|
| 251 |
+
text_threshold=0.5, mag_ratio=4.0,
|
| 252 |
+
allowlist='0123456789.', batch_size=4, y_ths=0.2)
|
| 253 |
|
| 254 |
best_weight = None
|
| 255 |
best_conf = 0.0
|
| 256 |
best_score = 0.0
|
| 257 |
for (bbox, text, conf) in results:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
text = re.sub(r"[^\d\.]", "", text)
|
| 259 |
if text.count('.') > 1:
|
| 260 |
+
text = text.replace('.', '', text.count('.') - 1)
|
|
|
|
| 261 |
text = text.strip('.')
|
| 262 |
+
if re.fullmatch(r"^\d*\.?\d+$", text):
|
| 263 |
try:
|
| 264 |
weight = float(text)
|
| 265 |
+
range_score = 1.5 if 0.1 <= weight <= 300 else 0.8
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
digit_count = len(text.replace('.', ''))
|
| 267 |
+
digit_score = 1.3 if 2 <= digit_count <= 5 else 0.9
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
score = conf * range_score * digit_score
|
| 269 |
if roi_bbox:
|
| 270 |
(x_roi, y_roi, w_roi, h_roi) = roi_bbox
|
|
|
|
| 272 |
x_min, y_min = int(min(b[0] for b in bbox)), int(min(b[1] for b in bbox))
|
| 273 |
x_max, y_max = int(max(b[0] for b in bbox)), int(max(b[1] for b in bbox))
|
| 274 |
bbox_area = (x_max - x_min) * (y_max - y_min)
|
| 275 |
+
if roi_area > 0 and bbox_area / roi_area < 0.05:
|
| 276 |
+
score *= 0.6
|
|
|
|
|
|
|
|
|
|
| 277 |
if score > best_score and conf > conf_threshold:
|
| 278 |
best_weight = text
|
| 279 |
best_conf = conf
|
|
|
|
| 287 |
logging.info("No valid weight detected after all attempts.")
|
| 288 |
return "Not detected", 0.0
|
| 289 |
|
| 290 |
+
# Format the weight
|
| 291 |
if "." in best_weight:
|
| 292 |
int_part, dec_part = best_weight.split(".")
|
| 293 |
int_part = int_part.lstrip("0") or "0"
|
| 294 |
dec_part = dec_part.rstrip('0')
|
| 295 |
+
best_weight = f"{int_part}.{dec_part}" if dec_part else int_part
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
else:
|
| 297 |
best_weight = best_weight.lstrip('0') or "0"
|
| 298 |
|
| 299 |
try:
|
| 300 |
+
final_weight = float(best_weight)
|
| 301 |
+
if final_weight < 0.1 or final_weight > 300:
|
| 302 |
+
best_conf *= 0.7
|
|
|
|
| 303 |
except ValueError:
|
| 304 |
pass
|
| 305 |
|