File size: 1,223 Bytes
6b14fa5
65ed4c1
8fe1b94
a71f519
6b14fa5
 
65ed4c1
363a646
65ed4c1
363a646
65ed4c1
029a668
363a646
33069a9
376b89d
029a668
376b89d
029a668
376b89d
029a668
 
33069a9
f0bddce
 
a71f519
029a668
33069a9
376b89d
 
65ed4c1
f0bddce
029a668
376b89d
029a668
 
 
f0bddce
 
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
31
32
33
34
35
36
37
38
39
40
41
42
import easyocr
import numpy as np
import cv2
import re

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

def extract_weight_from_image(pil_img):
    try:
        img = np.array(pil_img)

        # Convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        # Resize and enhance contrast
        gray = cv2.resize(gray, None, fx=2, fy=2, interpolation=cv2.INTER_LINEAR)
        gray = cv2.equalizeHist(gray)

        # Reduce noise and invert for LCD displays
        gray = cv2.GaussianBlur(gray, (3, 3), 0)
        inverted = cv2.bitwise_not(gray)

        # OCR
        result = reader.readtext(inverted, detail=0)
        combined_text = " ".join(result)
        print("OCR Result:", combined_text)

        # Primary match: e.g., 25kg, 75.45 kg
        match = re.search(r"(\d{1,3}(?:\.\d{1,2})?)\s?(kg|KG|Kg)", combined_text)
        if match:
            return f"{match.group(1)} kg", 95.0

        # Fallback: just numbers (assume it's in kg)
        fallback = re.search(r"\d{1,4}(?:\.\d{1,2})?", combined_text)
        if fallback:
            return f"{fallback.group(0)} kg", 75.0

        return "No weight detected kg", 0.0

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