Download v0.2/lines.py from ampixa/nepali-tiny-ocr: direct link, hf CLI and curl.
- Browser
- Download file 1.9 kB
-
https://huggingface.co/ampixa/nepali-tiny-ocr/resolve/main/v0.2/lines.py
- Command line
-
hf download hf://ampixa/nepali-tiny-ocr/v0.2/lines.py
-
curl -L -o lines.py https://huggingface.co/ampixa/nepali-tiny-ocr/resolve/main/v0.2/lines.py
1.9 kB
| """Line image loading shared by training and evaluation, so both see the same preprocessing.""" | |
| import numpy as np, cv2 | |
| H = 32 | |
| def text_band(gray): | |
| """Crop to the main band of ink rows plus a fixed margin, so text fills the same share of the height however the crop was made. Adds no parameters.""" | |
| h = gray.shape[0] | |
| if h < 8: return gray | |
| lo, hi = float(gray.min()), float(np.percentile(gray, 90)) | |
| if hi - lo < 30: return gray | |
| prof = (gray < (lo + hi) / 2).mean(1); on = prof > max(.01, .15 * prof.max()); best = (0, 0); s = None | |
| for i, v in enumerate(list(on) + [False]): | |
| if v and s is None: s = i | |
| if not v and s is not None: | |
| if prof[s:i].sum() > prof[best[0]:best[1]].sum(): best = (s, i) | |
| s = None | |
| a, b = best | |
| if b - a < 4: return gray | |
| # extend over faint rows holding vowel signs and lower marks, then add a margin | |
| n = b - a; a2 = max(0, a - int(.35 * n)); b2 = min(h, b + int(.35 * n)); m = int(.1 * n) + 1 | |
| while a2 > 0 and a > a2 and prof[a2:a].max() < .002: a2 += 1; break | |
| return gray[max(0, a2 - m):min(h, b2 + m)] | |
| def prep(gray, H=32, norm=False): | |
| if norm: gray = text_band(gray) | |
| h, w = gray.shape[:2]; nw = max(8, min(4096, round(w * H / max(1, h)))) | |
| g = cv2.resize(gray, (nw, H), interpolation=cv2.INTER_AREA if h > H else cv2.INTER_LINEAR).astype(np.float32) | |
| return 1 - g / 255 | |
| def batch(arrs): | |
| H = arrs[0].shape[0]; W = max(a.shape[1] for a in arrs); W += (-W) % 8; x = np.zeros((len(arrs), 1, H, W), np.float32) | |
| for i, a in enumerate(arrs): x[i, 0, :, :a.shape[1]] = a | |
| return x, np.array([a.shape[1] for a in arrs], np.int64) | |
| def crop(gray, box): | |
| x0, y0, x1, y1 = box; h = y1 - y0; px, py = .3 * h, .2 * h | |
| X0, Y0, X1, Y1 = int(max(0, x0 - px)), int(max(0, y0 - py)), int(x1 + px), int(y1 + py) | |
| c = gray[Y0:Y1, X0:X1]; return c if c.size else gray[:8, :8] | |