-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanswer.py
More file actions
49 lines (40 loc) · 1.44 KB
/
answer.py
File metadata and controls
49 lines (40 loc) · 1.44 KB
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
import cv2
import numpy as np
def func(input_path, dataset_path, output_path):
# Load test image
img = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE)
if img is None:
raise FileNotFoundError(f"Input image not found: {input_path}")
# Load templates
templates = {}
for i in range(10):
path = dataset_path + "/" + str(i) + ".png"
templates[str(i)] = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
# Parameters
threshold = 0.8
detections = []
# Run template matching for each digit
for digit, tmpl in templates.items():
result = cv2.matchTemplate(img, tmpl, cv2.TM_CCOEFF_NORMED)
yloc, xloc = np.where(result >= threshold)
for (x, y) in zip(xloc, yloc):
h, w = tmpl.shape
detections.append((x, y, x + w, y + h, digit, result[y, x]))
# Sort detections by x coordinate
detections.sort(key=lambda tup: tup[0])
# Filter overlapping boxes (naively)
filtered = []
prev_x = -100
for det in detections:
x1, y1, x2, y2, digit, score = det
if x1 - prev_x > 10: # simple distance filter
filtered.append((x1, y1, x2, y2, digit))
prev_x = x1
# Build recognized number
recognized = ""
for (_, _, _, _, digit) in filtered:
recognized += digit
# Save result to text file
with open(output_path, 'w') as f:
f.write(recognized)
func('simple_test.png', 'simple_templates', 'res.txt')