File size: 1,523 Bytes
ee1d691
65ed4c1
8fe1b94
a71f519
6b14fa5
ee1d691
 
363a646
65ed4c1
363a646
65ed4c1
1f19915
ee1d691
363a646
1f19915
83e0faf
ee1d691
1f19915
 
ee1d691
1f19915
ee1d691
 
83e0faf
ee1d691
 
 
1f19915
 
 
 
 
 
83e0faf
e91f073
83e0faf
1f19915
103f82b
ee1d691
 
103f82b
ee1d691
 
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
43
44
45
46
47
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)

        # Resize and grayscale
        img = cv2.resize(img, None, fx=3.5, fy=3.5, interpolation=cv2.INTER_LINEAR)
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        # Denoise & Adaptive Thresholding
        gray = cv2.bilateralFilter(gray, 11, 17, 17)
        thresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                       cv2.THRESH_BINARY_INV, 11, 2)

        # Run OCR
        results = reader.readtext(thresh)

        print("OCR Results:", results)

        weight_candidates = []
        for _, text, conf in results:
            cleaned = text.lower()
            cleaned = cleaned.replace("kg", "").replace("kgs", "")
            cleaned = cleaned.replace("o", "0").replace("O", "0")
            cleaned = cleaned.replace("s", "5").replace("S", "5")
            cleaned = cleaned.replace("g", "9").replace("G", "6")

            cleaned = re.sub(r"[^\d\.]", "", cleaned)

            if re.fullmatch(r"\d{2,4}(\.\d{1,2})?", cleaned):
                weight_candidates.append((cleaned, conf))

        if not weight_candidates:
            return "Not detected", 0.0

        best_weight, best_conf = sorted(weight_candidates, key=lambda x: -x[1])[0]
        return best_weight, round(best_conf * 100, 2)

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