File size: 1,103 Bytes
65ed4c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import easyocr
import numpy as np
import re
import cv2

reader = easyocr.Reader(['en'], gpu=False)

def extract_weight_from_image(pil_image):
    try:
        image = np.array(pil_image)

        # Grayscale conversion
        gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

        # Resize to make digits clearer
        resized = cv2.resize(gray, None, fx=3, fy=3, interpolation=cv2.INTER_CUBIC)

        # Bilateral Filter to reduce noise
        filtered = cv2.bilateralFilter(resized, 11, 17, 17)

        # Adaptive Thresholding
        thresh = cv2.adaptiveThreshold(filtered, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                       cv2.THRESH_BINARY, 11, 2)

        # OCR
        result = reader.readtext(thresh, detail=0)
        text = " ".join(result)
        print("OCR Output:", text)

        # Extract weight like 25.52 or 123
        match = re.search(r'\d{1,4}(\.\d{1,2})?', text)
        if match:
            return match.group(), 95.0
        else:
            return "No weight detected", 0.0

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