|
| 1 | +.. {#torchvision_preprocessing_converter} |
| 2 | +
|
| 3 | +Torchvision preprocessing converter |
| 4 | +======================================= |
| 5 | + |
| 6 | + |
| 7 | +.. meta:: |
| 8 | + :description: See how OpenVINO™ enables torchvision preprocessing |
| 9 | + to optimize model inference. |
| 10 | + |
| 11 | + |
| 12 | +The Torchvision-to-OpenVINO converter enables automatic translation of operators from the torchvision |
| 13 | +preprocessing pipeline to the OpenVINO format and embed them in your model. It is often used to adjust |
| 14 | +images serving as input for AI models to have proper dimensions or data types. |
| 15 | + |
| 16 | +As the converter is fully based on the **openvino.preprocess** module, you can implement the **torchvision.transforms** |
| 17 | +feature easily and without the use of external libraries, reducing the overall application complexity |
| 18 | +and enabling additional performance optimizations. |
| 19 | + |
| 20 | + |
| 21 | +.. note:: |
| 22 | + |
| 23 | + Not all torchvision transforms are supported yet. The following operations are available: |
| 24 | + |
| 25 | + .. code-block:: |
| 26 | +
|
| 27 | + transforms.Compose |
| 28 | + transforms.Normalize |
| 29 | + transforms.ConvertImageDtype |
| 30 | + transforms.Grayscale |
| 31 | + transforms.Pad |
| 32 | + transforms.ToTensor |
| 33 | + transforms.CenterCrop |
| 34 | + transforms.Resize |
| 35 | +
|
| 36 | +
|
| 37 | +Example |
| 38 | +################### |
| 39 | + |
| 40 | +.. code-block:: py |
| 41 | +
|
| 42 | + preprocess_pipeline = torchvision.transforms.Compose( |
| 43 | + [ |
| 44 | + torchvision.transforms.Resize(256, interpolation=transforms.InterpolationMode.NEAREST), |
| 45 | + torchvision.transforms.CenterCrop((216, 218)), |
| 46 | + torchvision.transforms.Pad((2, 3, 4, 5), fill=3), |
| 47 | + torchvision.transforms.ToTensor(), |
| 48 | + torchvision.transforms.ConvertImageDtype(torch.float32), |
| 49 | + torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), |
| 50 | + ] |
| 51 | + ) |
| 52 | +
|
| 53 | + torch_model = SimpleConvnet(input_channels=3) |
| 54 | +
|
| 55 | + torch.onnx.export(torch_model, torch.randn(1, 3, 224, 224), "test_convnet.onnx", verbose=False, input_names=["input"], output_names=["output"]) |
| 56 | + core = Core() |
| 57 | + ov_model = core.read_model(model="test_convnet.onnx") |
| 58 | +
|
| 59 | + test_input = np.random.randint(255, size=(260, 260, 3), dtype=np.uint16) |
| 60 | + ov_model = PreprocessConverter.from_torchvision( |
| 61 | + model=ov_model, transform=preprocess_pipeline, input_example=Image.fromarray(test_input.astype("uint8"), "RGB") |
| 62 | + ) |
| 63 | + ov_model = core.compile_model(ov_model, "CPU") |
| 64 | + ov_input = np.expand_dims(test_input, axis=0) |
| 65 | + output = ov_model.output(0) |
| 66 | + ov_result = ov_model(ov_input)[output] |
| 67 | +
|
| 68 | +
|
| 69 | +
|
| 70 | +
|
| 71 | +
|
0 commit comments