-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandwriting_processor.py
More file actions
157 lines (133 loc) · 5.49 KB
/
Copy pathhandwriting_processor.py
File metadata and controls
157 lines (133 loc) · 5.49 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
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
import os
import json
import numpy as np
from PIL import Image
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
from skimage.morphology import skeletonize
def extract_strokes(binary_img):
"""
Given a binary image of one character, skeletonize it and extract stroke points,
breaking into separate strokes if large jumps occur.
"""
skel = skeletonize(binary_img)
visited = np.zeros_like(skel, dtype=bool)
height, width = skel.shape
def neighbors(y, x):
for j in [-1, 0, 1]:
for i in [-1, 0, 1]:
if i == 0 and j == 0:
continue
ny, nx = y + j, x + i
if 0 <= ny < height and 0 <= nx < width:
yield ny, nx
strokes = []
for y in range(height):
for x in range(width):
if skel[y, x] and not visited[y, x]:
stack = [(y, x)]
stroke = []
last_point = None
while stack:
cy, cx = stack.pop()
if visited[cy, cx]:
continue
visited[cy, cx] = True
curr_point = np.array([cx, cy])
if last_point is not None:
dist = np.linalg.norm(curr_point - last_point)
if dist > 15: # Distance threshold to break rogue jump
stroke.append(["UP", "UP", 0])
strokes.extend(stroke)
stroke = []
stroke.append([int(cx), int(cy), 1])
last_point = curr_point
for ny, nx in neighbors(cy, cx):
if skel[ny, nx] and not visited[ny, nx]:
stack.append((ny, nx))
if stroke:
stroke.append(["UP", "UP", 0])
strokes.extend(stroke)
return strokes
def chaikin_smooth(stroke, iterations=2):
"""
Applies Chaikin's corner-cutting algorithm to smooth a stroke.
"""
for _ in range(iterations):
new_stroke = []
for i in range(len(stroke) - 1):
p0 = np.array(stroke[i][:2])
p1 = np.array(stroke[i+1][:2])
Q = 0.75 * p0 + 0.25 * p1
R = 0.25 * p0 + 0.75 * p1
new_stroke.extend([[int(Q[0]), int(Q[1]), 1], [int(R[0]), int(R[1]), 1]])
stroke = new_stroke
return stroke
def generate_strokes_json(image_path: str, json_out_path: str) -> dict:
"""
Extracts strokes from a labeled handwriting grid and saves them to json_out_path.
Returns the dict with strokes.
"""
# Load and scale image
img_np = np.array(Image.open(image_path))
height, width = img_np.shape[:2]
ref_width, ref_height = 2092, 1584
scaleX, scaleY = width / ref_width, height / ref_height
# Grid and labels
rows_per_section, cols = [3, 3, 2], 10
labels = (list("abcdefghijklmnopqrstuvwxyz") + [""] * 4 +
list("ABCDEFGHIJKLMNOPQRSTUVWXYZ") + [""] * 4 +
list("0123456789,.!?();") + [""] * 3)
assert len(labels) == sum(rows_per_section) * cols
start_x, start_y = int(172 * scaleX), int(330 * scaleY)
box_w, box_h = int(172 * scaleX), int(118 * scaleY)
row_spacing = int(128 * scaleY)
margin_x, margin_y = 38, 16
stroke_data = {}
label_idx = 0
curr_y = start_y
for section_rows in rows_per_section:
for r in range(section_rows):
for c in range(cols):
x1 = start_x + c * box_w
y1 = curr_y + r * box_h
x2 = x1 + box_w
y2 = y1 + box_h
# Crop character box with margin
char_img = img_np[
y1 + margin_y : y2 - margin_y,
x1 + margin_x : x2 - margin_x
]
# Convert to grayscale and threshold
gray = rgb2gray(char_img)
thresh = threshold_otsu(gray)
binary = gray < thresh
label = labels[label_idx]
if label:
strokes = extract_strokes(binary)
smoothed = []
segment = []
for point in strokes:
if point[0] == "UP":
if len(segment) >= 2:
smoothed.extend(chaikin_smooth(segment))
segment = []
smoothed.append(point)
else:
segment.append(point)
if len(segment) >= 2:
smoothed.extend(chaikin_smooth(segment))
stroke_data[label] = smoothed
label_idx += 1
curr_y += section_rows * box_h + row_spacing
os.makedirs(os.path.dirname(json_out_path), exist_ok=True)
with open(json_out_path, "w") as f:
json.dump(stroke_data, f, indent=2)
print(f"✅ Smooth strokes.json generated with {len(stroke_data)} characters.")
return stroke_data
if __name__ == "__main__":
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
img_path = os.path.join(BASE_DIR, "uploads", "handwriting.jpg")
json_out = os.path.join(BASE_DIR, "output", "strokes.json")
generate_strokes_json(img_path, json_out)