CoolFace
Modelpublic

institutional/institutional-books-visual-elements-orientation

sourceHugging Faceapache-2.0updated 1mo agoView on Hugging Face
0likes
Model Card

πŸ“š Institutional Books β€” Visual Elements Orientation Model (EfficientNetV2-M)

A 4‑class image classification model that predicts the rotation correction needed to restore visual elements from digitized book page scans to upright orientation. This model operates on cropped regions (e.g., images, diagrams, ornaments) and is intended as a post-processing stage after visual-element detection.

More information:

See also:

The Institutional Data Initiative at Harvard Law School Library works with knowledge institutionsβ€”from libraries and museums to cultural groups and government agenciesβ€”to refine and publish their collections as data. Reach out to collaborate on your collections.


Outline


Model Description

  • β€”Architecture: EfficientNetV2-M
  • β€”Parameters: 52,863,480
  • β€”Classes (corrections): 4
  • β€”Input resolution (train/inference): 480Γ—480 px crops (from 512Γ—512 resize)
  • β€”Framework: PyTorch

The model predicts the inverse rotation required to correct each crop back to upright. Input crops may be in any of four orientations; the model outputs one of four rotation labels.

Classes

The labels are β€œcorrection actions” to make the image upright:

Class indexLabelDescription
0uprightNo rotation needed (already upright)
1rotate_90_clockwiseRotate 90Β° clockwise to correct
2rotate_180Rotate 180Β° to correct
3rotate_90_counterclockwiseRotate 90Β° counter-clockwise to correct

Classes are mutually exclusive.

Intended Use

This model classifies the orientation of already-detected visual elements from digitized book pages.

Primary use cases:

  • β€”Correcting rotations of cropped visual elements in digitization pipelines
  • β€”Normalizing orientation before downstream tasks (captioning, OCR on musical scores, layout analysis)
  • β€”Quality control on large-scale digitized collections (flagging mis-rotate elements)

Out of scope:

  • β€”General full-page orientation detection (expects tight crops of a single element)
  • β€”Classification of semantic content (e.g., β€œimage vs. music”)
  • β€”Arbitrary-angle rotation beyond multiples of 90Β°

Training

Dataset

Source data consists of 7,904 manually curated crops of visual elements from the Institutional Books collection.

Original (pre-synthetic) label distribution (estimated, by source orientation):

  • β€”upright: 93.0%
  • β€”rotate_90_clockwise: 5.6%
  • β€”rotate_90_counterclockwise: 1.3%
  • β€”rotate_180: 0.03%

To avoid this extreme imbalance and to directly learn the correction operation:

  1. 1.All images were first manually corrected to upright.
  2. 2.Each upright image was synthetically rotated by 0Β°, 90Β°, 180Β°, and 270Β°.
  3. 3.The target label is the inverse rotation needed to restore the upright orientation.

Resulting synthetic orientation dataset:

  • β€”Total samples (with synthetic rotations): 31,616
  • β€”Train samples: 25,292
  • β€”Val samples: 3,160
  • β€”Test samples: 3,164
  • β€”Split: 0.8 / 0.1 / 0.1 (train / val / test)

Each original crop contributes four synthetic samples (one per orientation), producing a balanced label distribution across the four classes in the synthetic set.

Training Configuration

ParameterValue
BackboneEfficientNetV2-M
Classifier headDropout(p=0.3) β†’ Linear(1280, 4)
Image size (train)Resize(512Γ—512) β†’ RandomCrop(480Γ—480)
Image size (val/test)Resize(512Γ—512) β†’ CenterCrop(480Γ—480)
Batch size32
Max epochs20
Optimizer / LRNot specified (standard schedule)
NormalizationImageNet mean/std
HardwareSingle NVIDIA GH200 GPU
Total training time58 min 13 sec (20 epochs)
Avg. per epoch~2 min 55 sec
Train samples/epoch25,292 (~791 steps/epoch)
Throughput~145 images/sec

Data Augmentation (Train Only)

Preprocessing:

  • β€”Resize(512Γ—512)
  • β€”RandomCrop(480Γ—480)
  • β€”ColorJitter(brightness=0.2, contrast=0.2, saturation=0.1)

Stochastic augmentations:

AugmentationImplementationProbability
Random auto-contrastRandomAutocontrastp = 0.3
Random invertRandomInvertp = 0.15
Random grayscaleRandomGrayscalep = 0.2
Gaussian blurGaussianBlur(k=5, Οƒ=0.1–2.0)p = 1.0
Random erasingRandomErasing(scale=0.02–0.15)p = 0.2

Validation/Test preprocessing:

  • β€”Resize(512Γ—512)
  • β€”CenterCrop(480Γ—480)
  • β€”Normalize (ImageNet stats)

Evaluation

Per-Epoch Training Summary

On the validation set, accuracy increases steadily and plateaus around 90%, while validation loss begins to rise after approximately epoch 10, indicating moderate overfitting. Heavy augmentations successfully limit overfitting enough that the held-out test set slightly outperforms validation.

Final epoch (20):

  • β€”Train accuracy: 99.81%
  • β€”Val accuracy: 90.35%
  • β€”Train loss: 0.0058
  • β€”Val loss: 0.4753

Test Set Performance

On the held-out test set (3,164 samples; 791 per class):

  • β€”Overall accuracy: 91.34% (2,890 / 3,164)

Per-class accuracy:

ClassAccuracyCorrect / Total
upright91.78%726 / 791
rotate_90_clockwise89.76%710 / 791
rotate_18091.91%727 / 791
rotate_90_counterclockwise91.91%727 / 791

Additional notes:

  • β€”Misclassifications: 274 of the 3,164 test samples are misclassified (2,890 correct β†’ 91.34% overall accuracy). These break down per class as 65 (upright), 81 (rotate_90_clockwise), 64 (rotate_180), and 64 (rotate_90_counterclockwise).
  • β€”The 90Β° clockwise class is the most challenging, but still achieves close to 90% accuracy.

Inference Configuration

Typical inference settings:

ParameterValue
Image size512Γ—512 resize β†’ 480Γ—480 center crop
Batch size32 (tune for available GPU memory)
NormalizationImageNet mean/std
Output4-way softmax over orientation labels

The top-1 prediction corresponds to the rotation to apply to make the crop upright.

Usage

PyTorch Example

python
import torch
import torch.nn as nn
import torchvision.models as models
from torchvision import transforms
from huggingface_hub import hf_hub_download
from PIL import Image

# Download weights (the repo ships a state_dict at weights/weights.pth)
model_path = hf_hub_download(
    repo_id="institutional/institutional-books-visual-elements-orientation",
    filename="weights/weights.pth",
)

# Build the architecture and load the state_dict
model = models.efficientnet_v2_m(weights=None)
num_features = model.classifier[1].in_features
model.classifier = nn.Sequential(
    nn.Dropout(p=0.3, inplace=True),
    nn.Linear(num_features, 4),
)
state_dict = torch.load(model_path, map_location="cuda", weights_only=True)
model.load_state_dict(state_dict)
model.to("cuda")
model.eval()

# Preprocessing: match validation/test pipeline
preprocess = transforms.Compose([
    transforms.Resize((512, 512)),
    transforms.CenterCrop(480),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=[0.485, 0.456, 0.406],  # ImageNet
        std=[0.229, 0.224, 0.225],
    ),
])

idx_to_label = {
    0: "upright",
    1: "rotate_90_clockwise",
    2: "rotate_180",
    3: "rotate_90_counterclockwise",
}

# A high confidence threshold (0.99) is applied: predictions below it
# default to "upright" to minimize false corrections.
CONFIDENCE_THRESHOLD = 0.99

def predict_orientation(path):
    img = Image.open(path).convert("RGB")
    x = preprocess(img).unsqueeze(0).to("cuda")
    with torch.no_grad():
        logits = model(x)
        probs = torch.softmax(logits, dim=1)[0]
    top1 = int(torch.argmax(probs))
    conf = float(probs[top1])
    label = idx_to_label[top1] if conf >= CONFIDENCE_THRESHOLD else "upright"
    return label, conf, probs.cpu().tolist()

label, conf, all_probs = predict_orientation("crop.jpg")
print(f"Predicted correction: {label}, confidence: {conf:.3f}")

Applying Corrections

python
from PIL import Image

def apply_correction(img, label):
    if label == "upright":
        return img
    elif label == "rotate_90_clockwise":
        return img.rotate(-90, expand=True)
    elif label == "rotate_180":
        return img.rotate(180, expand=True)
    elif label == "rotate_90_counterclockwise":
        return img.rotate(90, expand=True)
    else:
        raise ValueError(f"Unknown label: {label}")

Limitations

  • β€”Trained specifically on crops from the Institutional Books collection. Performance may degrade on:
  • β€”Non-book imagery
  • β€”Heavily stylized or abstract content
  • β€”Very low-resolution or heavily compressed scans
  • β€”Supports only multiples of 90Β° rotations; does not handle slight skews or arbitrary angle rotations.
  • β€”Expected to work best when:
  • β€”Crops contain a clear visual object/structure
  • β€”Background is not overwhelmingly dominant
  • β€”Model assumes images are RGB; grayscale images are internally handled via standard preprocessing but not natively optimized for non-RGB channels.

Citation

bibtext
@misc{mendez2026institutionalbooksvisual,
      title={Institutional Books - Visual Elements: An open-source pipeline for extracting, classifying, deduplicating, and captioning visual elements from digital book collections}, 
      author={Jimmy Mendez and Matteo Cargnelutti and David Lowry-Duda and Catherine Brobston and Salwa Ismail and Greg Leppert and Amanda Watson and Jonathan Zittrain},
      year={2026},
      eprint={2608.18957},
      archivePrefix={arXiv},
      primaryClass={cs.CV},
      url={https://arxiv.org/abs/2608.18957}, 
}