|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. |
| 3 | + |
| 4 | +namespace Microsoft.Psi.Onnx |
| 5 | +{ |
| 6 | + using System; |
| 7 | + using System.Collections.Generic; |
| 8 | + using Microsoft.Psi; |
| 9 | + using Microsoft.Psi.Components; |
| 10 | + using Microsoft.Psi.Imaging; |
| 11 | + |
| 12 | + /// <summary> |
| 13 | + /// Component that runs an ImageNet image classification model. |
| 14 | + /// </summary> |
| 15 | + /// <remarks> |
| 16 | + /// This class implements a \psi component that runs an ONNX model trained |
| 17 | + /// on the ImageNet dataset that operates on 224x224 RGB images and scores |
| 18 | + /// the image for each of the 1000 ImageNet classes. It takes an input |
| 19 | + /// stream of \psi images, applies a center-crop, rescales and normalizes |
| 20 | + /// the pixel values into the input vector expected by the model. It also |
| 21 | + /// parses the model outputs into a list of <see cref="LabeledPrediction"/> |
| 22 | + /// values, corresponding to the top N predictions by the model. For |
| 23 | + /// convenience, a set of pre-defined model runner configurations are |
| 24 | + /// defined for a number of image classification models available in the |
| 25 | + /// ONNX Model Zoo (https://github.com/onnx/models/tree/master/vision/classification). |
| 26 | + /// The ONNX model file for the corresponding configuration will need to be |
| 27 | + /// downloaded locally and the path to the model file will need to be |
| 28 | + /// specified when creating the configuration. |
| 29 | + /// </remarks> |
| 30 | + public class ImageNetModelRunner : ConsumerProducer<Shared<Image>, List<LabeledPrediction>> |
| 31 | + { |
| 32 | + private readonly float[] onnxInputVector = new float[3 * 224 * 224]; |
| 33 | + private readonly OnnxModel onnxModel; |
| 34 | + private readonly ImageNetModelOutputParser outputParser; |
| 35 | + |
| 36 | + /// <summary> |
| 37 | + /// Initializes a new instance of the <see cref="ImageNetModelRunner"/> class. |
| 38 | + /// </summary> |
| 39 | + /// <param name="pipeline">The pipeline to add the component to.</param> |
| 40 | + /// <param name="configuration">The configuration for the compoinent.</param> |
| 41 | + /// <remarks> |
| 42 | + /// To run on a GPU, use the Microsoft.Psi.Onnx.ModelRunners.Gpu library instead of Microsoft.Psi.Onnx.ModelRunners.Cpu, and set |
| 43 | + /// the value of the <pararef name="gpuDeviceId"/> parameter to a valid non-negative integer. Typical device ID values are 0 or 1. |
| 44 | + /// </remarks> |
| 45 | + public ImageNetModelRunner(Pipeline pipeline, ImageNetModelRunnerConfiguration configuration) |
| 46 | + : base(pipeline) |
| 47 | + { |
| 48 | + // create an ONNX model based on the supplied ImageNet model runner configuration |
| 49 | + this.onnxModel = new OnnxModel(new OnnxModelConfiguration() |
| 50 | + { |
| 51 | + ModelFileName = configuration.ModelFilePath, |
| 52 | + InputVectorName = configuration.InputVectorName, |
| 53 | + InputVectorSize = 3 * 224 * 224, |
| 54 | + OutputVectorName = configuration.OutputVectorName, |
| 55 | + GpuDeviceId = configuration.GpuDeviceId, |
| 56 | + }); |
| 57 | + |
| 58 | + this.outputParser = new ImageNetModelOutputParser(configuration.ImageClassesFilePath, configuration.NumberOfPredictions, configuration.ApplySoftmaxToModelOutput); |
| 59 | + } |
| 60 | + |
| 61 | + /// <inheritdoc/> |
| 62 | + protected override void Receive(Shared<Image> data, Envelope envelope) |
| 63 | + { |
| 64 | + // construct the ONNX model input vector (stored in this.onnxInputVector) |
| 65 | + // based on the incoming image |
| 66 | + this.ConstructOnnxInputVector(data); |
| 67 | + |
| 68 | + // run the model over the input vector |
| 69 | + var outputVector = this.onnxModel.GetPrediction(this.onnxInputVector); |
| 70 | + |
| 71 | + // parse the model output into an ordered list of the top-N predictions |
| 72 | + var results = this.outputParser.GetPredictions(outputVector); |
| 73 | + |
| 74 | + // post the results |
| 75 | + this.Out.Post(results, envelope.OriginatingTime); |
| 76 | + } |
| 77 | + |
| 78 | + /// <summary> |
| 79 | + /// Constructs the input vector for the ImageNet model for a specified image. |
| 80 | + /// </summary> |
| 81 | + /// <param name="sharedImage">The image to construct the input vector for.</param> |
| 82 | + private void ConstructOnnxInputVector(Shared<Image> sharedImage) |
| 83 | + { |
| 84 | + var inputImage = sharedImage.Resource; |
| 85 | + var inputWidth = sharedImage.Resource.Width; |
| 86 | + var inputHeight = sharedImage.Resource.Height; |
| 87 | + |
| 88 | + // crop a center square |
| 89 | + var squareSize = Math.Min(inputWidth, inputHeight); |
| 90 | + using var squareImage = ImagePool.GetOrCreate(squareSize, squareSize, sharedImage.Resource.PixelFormat); |
| 91 | + if (inputWidth > inputHeight) |
| 92 | + { |
| 93 | + inputImage.Crop(squareImage.Resource, (inputWidth - squareSize) / 2, 0, squareSize, squareSize); |
| 94 | + } |
| 95 | + else |
| 96 | + { |
| 97 | + inputImage.Crop(squareImage.Resource, 0, (inputHeight - squareSize) / 2, squareSize, squareSize); |
| 98 | + } |
| 99 | + |
| 100 | + // resize the image to 224 x 224 |
| 101 | + using var resizedImage = ImagePool.GetOrCreate(224, 224, sharedImage.Resource.PixelFormat); |
| 102 | + squareImage.Resource.Resize(resizedImage.Resource, 224, 224, SamplingMode.Bilinear); |
| 103 | + |
| 104 | + // if the pixel format does not match, do a conversion before extracting the bytes |
| 105 | + var bytes = default(byte[]); |
| 106 | + if (sharedImage.Resource.PixelFormat != PixelFormat.BGR_24bpp) |
| 107 | + { |
| 108 | + using var reformattedImage = ImagePool.GetOrCreate(224, 224, PixelFormat.BGR_24bpp); |
| 109 | + resizedImage.Resource.CopyTo(reformattedImage.Resource); |
| 110 | + bytes = reformattedImage.Resource.ReadBytes(3 * 224 * 224); |
| 111 | + } |
| 112 | + else |
| 113 | + { |
| 114 | + // get the bytes |
| 115 | + bytes = resizedImage.Resource.ReadBytes(3 * 224 * 224); |
| 116 | + } |
| 117 | + |
| 118 | + // Now populate the onnxInputVector float array / tensor by normalizing |
| 119 | + // using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225]. |
| 120 | + int fi = 0; |
| 121 | + |
| 122 | + // first the red bytes |
| 123 | + for (int i = 2; i < bytes.Length; i += 3) |
| 124 | + { |
| 125 | + this.onnxInputVector[fi++] = ((bytes[i] / 255.0f) - 0.485f) / 0.229f; |
| 126 | + } |
| 127 | + |
| 128 | + // then the green bytes |
| 129 | + for (int i = 1; i < bytes.Length; i += 3) |
| 130 | + { |
| 131 | + this.onnxInputVector[fi++] = ((bytes[i] / 255.0f) - 0.456f) / 0.224f; |
| 132 | + } |
| 133 | + |
| 134 | + // then the blue bytes |
| 135 | + for (int i = 0; i < bytes.Length; i += 3) |
| 136 | + { |
| 137 | + this.onnxInputVector[fi++] = ((bytes[i] / 255.0f) - 0.406f) / 0.225f; |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | +} |
0 commit comments