|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | + |
1 | 4 | import cv2
|
2 | 5 | import numpy as np
|
| 6 | +import onnxruntime |
3 | 7 | import pytest
|
4 | 8 | import torch
|
5 | 9 |
|
6 | 10 | from doctr.models import classification
|
7 | 11 | from doctr.models.classification.predictor import CropOrientationPredictor
|
| 12 | +from doctr.models.utils import export_classification_model_to_onnx |
8 | 13 |
|
9 | 14 |
|
10 | 15 | def _test_classification(model, input_shape, output_size, batch_size=2):
|
@@ -98,3 +103,37 @@ def test_crop_orientation_model(mock_text_box):
|
98 | 103 | text_box_270 = np.rot90(text_box_0, 3)
|
99 | 104 | classifier = classification.crop_orientation_predictor("mobilenet_v3_small_orientation", pretrained=True)
|
100 | 105 | assert classifier([text_box_0, text_box_90, text_box_180, text_box_270]) == [0, 1, 2, 3]
|
| 106 | + |
| 107 | + |
| 108 | +@pytest.mark.parametrize( |
| 109 | + "arch_name, input_shape, output_size", |
| 110 | + [ |
| 111 | + ["vgg16_bn_r", (3, 32, 32), (126,)], |
| 112 | + ["resnet18", (3, 32, 32), (126,)], |
| 113 | + ["resnet31", (3, 32, 32), (126,)], |
| 114 | + ["resnet34", (3, 32, 32), (126,)], |
| 115 | + ["resnet34_wide", (3, 32, 32), (126,)], |
| 116 | + ["resnet50", (3, 32, 32), (126,)], |
| 117 | + ["magc_resnet31", (3, 32, 32), (126,)], |
| 118 | + ["mobilenet_v3_small", (3, 32, 32), (126,)], |
| 119 | + ["mobilenet_v3_large", (3, 32, 32), (126,)], |
| 120 | + ["mobilenet_v3_small_orientation", (3, 128, 128), (4,)], |
| 121 | + ], |
| 122 | +) |
| 123 | +def test_models_onnx_export(arch_name, input_shape, output_size): |
| 124 | + # Model |
| 125 | + batch_size = 2 |
| 126 | + model = classification.__dict__[arch_name](pretrained=True).eval() |
| 127 | + dummy_input = torch.rand((batch_size, *input_shape), dtype=torch.float32) |
| 128 | + with tempfile.TemporaryDirectory() as tmpdir: |
| 129 | + # Export |
| 130 | + model_path = export_classification_model_to_onnx(model, |
| 131 | + exp_name=os.path.join(tmpdir, "model"), |
| 132 | + dummy_input=dummy_input) |
| 133 | + assert os.path.exists(model_path) |
| 134 | + # Inference |
| 135 | + ort_session = onnxruntime.InferenceSession(os.path.join(tmpdir, "model.onnx"), |
| 136 | + providers=["CPUExecutionProvider"]) |
| 137 | + ort_outs = ort_session.run(['logits'], {'input': dummy_input.numpy()}) |
| 138 | + assert isinstance(ort_outs, list) and len(ort_outs) == 1 |
| 139 | + assert ort_outs[0].shape == (batch_size, *output_size) |
0 commit comments