microsoft/onnxruntime-extensions
Publicmirrored fromhttps://github.com/microsoft/onnxruntime-extensionsAvailable
operators/vision/encode_image.cc
44lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | #include "encode_image.hpp" |
| 5 | |
| 6 | #include <opencv2/imgcodecs.hpp> |
| 7 | |
| 8 | namespace ort_extensions { |
| 9 | |
| 10 | void KernelEncodeImage ::Compute(OrtKernelContext* context) { |
| 11 | // Setup inputs |
| 12 | const OrtValue* input_bgr = ort_.KernelContext_GetInput(context, 0ULL); |
| 13 | const OrtTensorDimensions dimensions_bgr(ort_, input_bgr); |
| 14 | |
| 15 | if (dimensions_bgr.size() != 3 || dimensions_bgr[2] != 3) { |
| 16 | // expect {H, W, C} as that's the inverse of what decode_image produces. |
| 17 | // we have no way to check if it's BGR or RGB though |
| 18 | ORTX_CXX_API_THROW("[EncodeImage] requires rank 3 BGR input in channels last format.", ORT_INVALID_ARGUMENT); |
| 19 | } |
| 20 | |
| 21 | // Get data & the length |
| 22 | std::vector<int32_t> height_x_width{static_cast<int32_t>(dimensions_bgr[0]), // H |
| 23 | static_cast<int32_t>(dimensions_bgr[1])}; // W |
| 24 | |
| 25 | // data is const uint8_t but opencv2 wants void*. |
| 26 | const void* bgr_data = ort_.GetTensorData<uint8_t>(input_bgr); |
| 27 | const cv::Mat bgr_image(height_x_width, CV_8UC3, const_cast<void*>(bgr_data)); |
| 28 | |
| 29 | // don't know output size ahead of time so need to encode and then copy to output |
| 30 | std::vector<uint8_t> encoded_image; |
| 31 | if (!cv::imencode(extension_, bgr_image, encoded_image)) { |
| 32 | ORTX_CXX_API_THROW("[EncodeImage] Image encoding failed.", ORT_INVALID_ARGUMENT); |
| 33 | } |
| 34 | |
| 35 | // Setup output & copy to destination |
| 36 | std::vector<int64_t> output_dimensions{static_cast<int64_t>(encoded_image.size())}; |
| 37 | OrtValue* output_value = ort_.KernelContext_GetOutput(context, 0, |
| 38 | output_dimensions.data(), |
| 39 | output_dimensions.size()); |
| 40 | |
| 41 | uint8_t* data = ort_.GetTensorMutableData<uint8_t>(output_value); |
| 42 | memcpy(data, encoded_image.data(), encoded_image.size()); |
| 43 | } |
| 44 | } // namespace ort_extensions |
| 45 | |