File size: 7,394 Bytes
363e479
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import cv2
import easyocr
import numpy as np
import json
import sys
import os
import re

# ─────────────────────────────────────────────
#  CONFIGURATION
# ─────────────────────────────────────────────
OCR_LANGUAGES     = ['en']
MIN_OCR_CONF      = 0.4     # raised to filter junk text
IC_LABELS         = ['ic', 'transistor', 'clock', 'display']
PADDING           = 10

# Junk patterns to filter out from OCR results
JUNK_PATTERNS = [
    r'^[^a-zA-Z0-9]+$',   # only symbols
    r'^\d{1,2}$',          # single/double digit only (too short to be useful)
    r'^[a-zA-Z]{1}$',      # single letter
]

# ─────────────────────────────────────────────
#  INITIALIZE READER
# ─────────────────────────────────────────────
print("[->] Loading EasyOCR model...")
reader = easyocr.Reader(OCR_LANGUAGES, gpu=True)
print("[OK] EasyOCR ready")


# ─────────────────────────────────────────────
#  FILTER JUNK OCR TEXT
# ─────────────────────────────────────────────
def is_junk(text: str) -> bool:
    for pattern in JUNK_PATTERNS:
        if re.match(pattern, text):
            return True
    return False


# ─────────────────────────────────────────────
#  PREPROCESS CHIP PATCH
# ─────────────────────────────────────────────
def preprocess_patch(patch: np.ndarray) -> np.ndarray:
    h, w = patch.shape[:2]
    # Only upscale if patch is small
    scale = 3 if max(h, w) < 100 else 2
    upscaled  = cv2.resize(patch, (w * scale, h * scale),
                            interpolation=cv2.INTER_CUBIC)
    kernel    = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]])
    sharpened = cv2.filter2D(upscaled, -1, kernel)
    denoised  = cv2.fastNlMeansDenoisingColored(sharpened, h=10)
    return denoised


# ─────────────────────────────────────────────
#  RUN OCR ON A SINGLE PATCH
# ─────────────────────────────────────────────
def read_text_from_patch(patch: np.ndarray) -> list:
    processed = preprocess_patch(patch)
    results   = reader.readtext(processed)

    texts = []
    for (_, text, conf) in results:
        text = text.strip()
        if conf >= MIN_OCR_CONF and len(text) >= 2 and not is_junk(text):
            texts.append((text, round(conf, 3)))

    return texts


# ─────────────────────────────────────────────
#  RUN OCR ON ALL IC DETECTIONS
# ─────────────────────────────────────────────
def run_ocr_on_detections(image_path: str, detections: list) -> list:
    img = cv2.imread(image_path)
    if img is None:
        print(f"[X] Could not load image: {image_path}")
        return detections

    ih, iw = img.shape[:2]
    updated  = []

    ic_count = sum(1 for d in detections if d['label'] in IC_LABELS)
    print(f"\n[->] Running OCR on {ic_count} IC/chip regions...")

    for det in detections:
        label = det['label']

        if label not in IC_LABELS:
            det['ocr_text']   = []
            det['part_number']= "N/A"
            updated.append(det)
            continue

        x1, y1, x2, y2 = det['bbox']
        x1p = max(0,  x1 - PADDING)
        y1p = max(0,  y1 - PADDING)
        x2p = min(iw, x2 + PADDING)
        y2p = min(ih, y2 + PADDING)

        patch = img[y1p:y2p, x1p:x2p]

        if patch.size == 0:
            det['ocr_text']    = []
            det['part_number'] = "unknown"
            updated.append(det)
            continue

        texts    = read_text_from_patch(patch)
        combined = " ".join(t for t, c in texts).strip()

        det['ocr_text']    = texts
        det['part_number'] = combined if combined else "unknown"

        if texts:
            print(f"   [{label}] @ ({x1},{y1}) β†’ '{combined}'")
        else:
            print(f"   [{label}] @ ({x1},{y1}) β†’ (no text detected)")

        updated.append(det)

    return updated


# ─────────────────────────────────────────────
#  PRINT OCR SUMMARY
# ─────────────────────────────────────────────
def print_ocr_summary(detections: list):
    ic_dets = [d for d in detections if d['label'] in IC_LABELS]
    identified = [d for d in ic_dets if d.get('part_number', 'unknown') not in ('unknown', 'N/A', '')]

    print(f"\n-- OCR Summary ---------------------------")
    for det in ic_dets:
        label = det['label']
        part  = det.get('part_number', 'unknown')
        conf  = det['confidence']
        hits  = len(det.get('ocr_text', []))
        print(f"   {label:<15} | part: {part:<30} | conf: {conf:.0%} | ocr hits: {hits}")
    print(f"\n   Total ICs/chips : {len(ic_dets)}")
    print(f"   Text identified : {len(identified)}")
    print(f"------------------------------------------\n")


# ─────────────────────────────────────────────
#  ENTRY POINT
# ─────────────────────────────────────────────
if __name__ == "__main__":
    if len(sys.argv) < 3:
        print("Usage: python ocr.py <image_path> <results_json>")
        print("Example: python ocr.py sample5.jpg sample5_results.json")
        sys.exit(1)

    image_path   = sys.argv[1]
    results_json = sys.argv[2]

    with open(results_json) as f:
        data = json.load(f)

    detections = data.get("components", [])
    for d in detections:
        d['bbox'] = tuple(d['bbox'])

    print(f"[OK] Loaded {len(detections)} detections from {results_json}")

    updated = run_ocr_on_detections(image_path, detections)
    print_ocr_summary(updated)

    # Save updated JSON
    base     = os.path.splitext(results_json)[0]
    out_path = base + "_ocr.json"
    out_data = {
        "total_components": len(updated),
        "components": [
            {**d,
             "bbox":     list(d["bbox"]),
             "ocr_text": [[t, c] for t, c in d.get("ocr_text", [])]}
            for d in updated
        ]
    }
    with open(out_path, "w") as f:
        json.dump(out_data, f, indent=2)
    print(f"[OK] Updated results saved: {out_path}")