File size: 823 Bytes
372ab96
65ed4c1
8fe1b94
a71f519
6b14fa5
363a646
65ed4c1
372ab96
363a646
65ed4c1
372ab96
 
363a646
e91f073
372ab96
 
103f82b
372ab96
 
 
103f82b
372ab96
 
 
 
 
8fe1b94
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
import pytesseract
import numpy as np
import cv2
import re

def extract_weight_from_image(pil_img):
    try:
        # Convert PIL to OpenCV format
        img = np.array(pil_img)

        # Resize and convert to grayscale
        img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        # Thresholding for clarity
        _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)

        # Run OCR
        text = pytesseract.image_to_string(thresh)
        print("OCR TEXT:", text)

        # Search for weight pattern
        match = re.search(r"\b\d{2,4}(\.\d{1,2})?\b", text)
        if match:
            return match.group(), 99.0
        return "Not detected", 0.0

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