File size: 1,467 Bytes
c11fb3a
 
8f557ef
 
 
 
c11fb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
7605648
c11fb3a
 
 
 
 
 
 
1362c73
45d0a85
c11fb3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42b463a
393f381
c11fb3a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import easyocr
import re
import cv2
import numpy as np
from PIL import Image

# Initialize EasyOCR reader (only once)
reader = easyocr.Reader(['en'], gpu=False)

def preprocess_image(image):
    # Convert to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

    # Apply thresholding (adaptive works well for 7-seg)
    thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                   cv2.THRESH_BINARY_INV, 15, 10)

    # Dilation to strengthen numbers
    kernel = np.ones((2, 2), np.uint8)
    dilated = cv2.dilate(thresh, kernel, iterations=1)

    return dilated

def extract_weight_from_image(pil_image):
    try:
        # Convert PIL to OpenCV
        image = np.array(pil_image.convert("RGB"))
        processed = preprocess_image(image)

        # OCR
        result = reader.readtext(processed)

        # Filter and extract digits like weight (e.g., 75.5)
        weight = None
        confidence = 0.0
        for detection in result:
            text = detection[1]
            conf = detection[2]
            match = re.search(r"\d{2,4}(\.\d{1,2})?", text)  # match 2-4 digit decimal
            if match:
                weight = match.group()
                confidence = conf
                break

        if weight:
            return weight, round(confidence * 100, 2)
        else:
            return "No weight detected", 0.0

    except Exception as e:
        return f"Error: {str(e)}", 0.0