microsoft/onnxruntime-extensions
Publicmirrored fromhttps://github.com/microsoft/onnxruntime-extensionsAvailable
operators/vision/decode_image.cc
44lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | #include "decode_image.hpp" |
| 5 | |
| 6 | #include <opencv2/imgcodecs.hpp> |
| 7 | #include "narrow.h" |
| 8 | |
| 9 | namespace ort_extensions { |
| 10 | |
| 11 | void KernelDecodeImage::Compute(OrtKernelContext* context) { |
| 12 | // Setup inputs |
| 13 | const OrtValue* const inputs = ort_.KernelContext_GetInput(context, 0ULL); |
| 14 | OrtTensorDimensions dimensions(ort_, inputs); |
| 15 | if (dimensions.size() != 1ULL) { |
| 16 | ORTX_CXX_API_THROW("[DecodeImage]: Raw image bytes with 1D shape expected.", ORT_INVALID_ARGUMENT); |
| 17 | } |
| 18 | |
| 19 | OrtTensorTypeAndShapeInfo* input_info = ort_.GetTensorTypeAndShape(inputs); |
| 20 | const int64_t encoded_image_data_len = ort_.GetTensorShapeElementCount(input_info); |
| 21 | ort_.ReleaseTensorTypeAndShapeInfo(input_info); |
| 22 | |
| 23 | // Decode the image |
| 24 | const std::vector<int32_t> encoded_image_sizes{1, static_cast<int32_t>(encoded_image_data_len)}; |
| 25 | const void* encoded_image_data = ort_.GetTensorData<uint8_t>(inputs); // uint8 data |
| 26 | const cv::Mat encoded_image(encoded_image_sizes, CV_8UC1, const_cast<void*>(encoded_image_data)); |
| 27 | const cv::Mat decoded_image = cv::imdecode(encoded_image, cv::IMREAD_COLOR); |
| 28 | |
| 29 | if (decoded_image.data == nullptr) { |
| 30 | ORTX_CXX_API_THROW("[DecodeImage] Invalid input. Failed to decode image.", ORT_INVALID_ARGUMENT); |
| 31 | }; |
| 32 | |
| 33 | // Setup output & copy to destination |
| 34 | const cv::Size decoded_image_size = decoded_image.size(); |
| 35 | const int64_t height = decoded_image_size.height; |
| 36 | const int64_t width = decoded_image_size.width; |
| 37 | const int64_t colors = decoded_image.elemSize(); // == 3 as it's BGR |
| 38 | |
| 39 | const std::vector<int64_t> output_dims{height, width, colors}; |
| 40 | OrtValue* output_value = ort_.KernelContext_GetOutput(context, 0, output_dims.data(), output_dims.size()); |
| 41 | uint8_t* decoded_image_data = ort_.GetTensorMutableData<uint8_t>(output_value); |
| 42 | memcpy(decoded_image_data, decoded_image.data, narrow<size_t>(height * width * colors)); |
| 43 | } |
| 44 | } // namespace ort_extensions |
| 45 | |