Japanese Character Recognition CNN

A Convolutional Neural Network (CNN) for classifying individual Japanese characters from 64x64 grayscale images. Four model versions are available: v3 (Jōyō + JIS Level 1) and v4 (adds JIS Level 2) are recommended for finger-drawn input.


v4 β€” PyTorch/ONNX, extended character set

KanjiDNN_v4.onnx β€” covers JIS Level 1 and Level 2 kanji (about twice the characters of v3), for finger-drawn input on touchscreens. Use v3 if you only need Jōyō + JIS Level 1 (smaller file).

Property Value
Framework PyTorch, exported to ONNX
Classes 6,541 (6,359 kanji: Jōyō + JIS Level 1 + JIS Level 2, 181 kana, 1 REJECT)
Input 64x64 grayscale, binarized, ink=1.0 / background=0.0 (input name image, output logits)
Parameters ~8.7M
File size 35 MB
Training data KanjiVG SVG strokes with finger-drawing and geometry augmentation + ETL9G handwriting samples

Accuracy

Held-out real ETL9G handwriting (writers not seen in training, 91,080 samples, JIS Level 1 kanji + hiragana):

Model Top-1 accuracy
v4 (6,541 classes) 98.6%
v3 (3,181 classes) 98.4%

Remaining errors are mostly look-alike pairs (粟/ζ —, ζœͺ/末, ζ’€/ζ’’) and kanji/kana twins such as ε·₯/エ and γ‚Š/γƒͺ, which need context to separate. Characters with 1–3 strokes score about 78% for that reason. JIS Level 2 kanji and katakana have no real handwriting in ETL9G, so they are trained (and only checkable) on synthetic data.

Architecture

4x ConvBlock(Conv3x3 β†’ BN β†’ ReLU β†’ Conv3x3 β†’ BN β†’ ReLU β†’ MaxPool2x2 β†’ Dropout)
  channels: 32 β†’ 64 β†’ 128 β†’ 256
1x ConvBlock without pooling: 256 β†’ 384 (at 4x4)
AdaptiveAvgPool β†’ Linear(384,768) β†’ BN β†’ ReLU β†’ Dropout(0.4) β†’ Linear(768, num_classes)

Trained with label smoothing 0.1, warm-started from an earlier extended model. Augmentation additionally shifts, scales and spaces the components of a kanji (e.g. a wide gap between 青 and δΊ‰ in 静) and jitters individual strokes, using the KanjiVG component groups.

Preprocessing and rejection

Identical to v3 (KanjiDNN_v4_preprocessing_config.json, KanjiDNN_v4_inference_config.json; REJECT is index 6540). Because of label smoothing, top-1 probabilities are lower than v3's: about 20% of correct predictions on real handwriting stay below 0.9, so use a lower threshold if you treat high confidence as "certain".

Usage (ONNX Runtime)

import onnxruntime as ort
import numpy as np
import json

session = ort.InferenceSession("KanjiDNN_v4.onnx")
classes = json.load(open("KanjiDNN_v4_classes.json"))

# image: preprocessed 64x64 float32 array, shape (1, 1, 64, 64)
image = np.expand_dims(np.expand_dims(preprocessed, 0), 0).astype(np.float32)
logits = session.run(None, {session.get_inputs()[0].name: image})[0]

probs = np.exp(logits - logits.max()) / np.exp(logits - logits.max()).sum()
top_idx = int(np.argmax(probs))
print(f"Prediction: {classes[top_idx]} ({probs[0][top_idx]:.1%})")

v3 β€” PyTorch/ONNX (recommended, smaller)

KanjiDNN_v3.onnx β€” a compact 4-block CNN optimized for finger-drawn input on touchscreens.

Property Value
Framework PyTorch, exported to ONNX
Classes 3,181 (2,140 Joyo kanji + 859 JIS Level 1 kanji + 181 kana + 1 REJECT)
Input 64x64 grayscale, binarized, ink=1.0 / background=0.0
Parameters ~2.4M
File size 11 MB
Training data KanjiVG SVG strokes with finger-drawing augmentation + ETL9G handwriting samples

Architecture

4x ConvBlock(Conv3x3 β†’ BN β†’ ReLU β†’ Conv3x3 β†’ BN β†’ ReLU β†’ MaxPool2x2 β†’ Dropout)
  channels: 32 β†’ 64 β†’ 128 β†’ 256
AdaptiveAvgPool β†’ Linear(256,512) β†’ BN β†’ ReLU β†’ Dropout(0.4) β†’ Linear(512, num_classes)

Preprocessing

Images must be preprocessed identically to training (see KanjiDNN_v3_preprocessing_config.json):

  1. Binarize at threshold 200
  2. Crop to ink bounding box
  3. Add margin (10% of the larger dimension)
  4. Resize to 64x64 (preserve aspect ratio, center on canvas)
  5. Normalize: (255 - pixel) / 255 (ink=1.0, background=0.0)

Rejection

Dual-layer rejection (see KanjiDNN_v3_inference_config.json):

  • Explicit REJECT class (index 3180) trained on romaji, digits, punctuation, scribbles, and blanks
  • Confidence threshold: force reject when top softmax probability < 0.5

Usage (ONNX Runtime)

import onnxruntime as ort
import numpy as np
import json

session = ort.InferenceSession("KanjiDNN_v3.onnx")
classes = json.load(open("KanjiDNN_v3_classes.json"))

# image: preprocessed 64x64 float32 array, shape (1, 1, 64, 64)
image = np.expand_dims(np.expand_dims(preprocessed, 0), 0).astype(np.float32)
logits = session.run(None, {"input": image})[0]

probs = np.exp(logits) / np.exp(logits).sum()
top_idx = np.argmax(probs)
print(f"Prediction: {classes[top_idx]} ({probs[0][top_idx]:.1%})")

Why v3?

Built to replace v1/v2, whose precision suffers on real finger input β€” their inference pipeline skips bounding-box centering and normalization. v3 uses KanjiVG strokes augmented to approximate finger-drawing (thick, imprecise strokes, no pressure taper) plus ETL9G handwriting samples, with a rigorous preprocessing pipeline that must be replicated at inference time.

Source code

Training pipeline: github.com/gaiseras/kanjirec (if public) β€” includes dataset generation, augmentation, training, evaluation, and ONNX export scripts.


v1 & v2 β€” Keras

KanjiDNN_v1.keras and KanjiDNN_v2.keras β€” the original Keras models.

Character classes

  • Kanji, Hiragana & Katakana (kana), Romaji (Latin letters), Digits (0-9), Common punctuation marks

Training data

Usage (Keras)

import os
os.environ["KERAS_BACKEND"] = "jax"  # or "torch", "tensorflow"
import keras

model = keras.saving.load_model("hf://gaiseras/kanjiDNN")

Try it live

Gradio demo on Hugging Face Spaces

Downloads last month
97
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support

Space using gaiseras/kanjiDNN 1