microsoft/onnxruntime-extensions
Publicmirrored fromhttps://github.com/microsoft/onnxruntime-extensionsAvailable
operators/cv2/imread.hpp
51lines · modecode
| 1 | #include <opencv2/core.hpp> |
| 2 | #include <opencv2/imgcodecs.hpp> |
| 3 | |
| 4 | #include "string_tensor.h" |
| 5 | |
| 6 | |
| 7 | struct KernelImageReader : BaseKernel { |
| 8 | KernelImageReader(const OrtApi& api) : BaseKernel(api) { |
| 9 | } |
| 10 | |
| 11 | void Compute(OrtKernelContext* context) { |
| 12 | const OrtValue* input_data = ort_.KernelContext_GetInput(context, 0); |
| 13 | OrtTensorDimensions input_data_dimensions(ort_, input_data); |
| 14 | |
| 15 | int n = input_data_dimensions[0]; |
| 16 | if (n != 1) { |
| 17 | ORTX_CXX_API_THROW("[ImageReader]: the dimension of input value can only be 1 now.", ORT_INVALID_ARGUMENT); |
| 18 | } |
| 19 | |
| 20 | std::vector<std::string> image_paths; |
| 21 | GetTensorMutableDataString(api_, ort_, context, input_data, image_paths); |
| 22 | |
| 23 | cv::Mat img = cv::imread(image_paths[0], cv::IMREAD_COLOR); |
| 24 | std::vector<int64_t> output_dimensions = {1, img.size[0], img.size[1], static_cast<int64_t>(img.elemSize())}; |
| 25 | OrtValue* output_image = ort_.KernelContext_GetOutput(context, 0, output_dimensions.data(), output_dimensions.size()); |
| 26 | std::uint8_t* p_output_image = ort_.GetTensorMutableData<uint8_t>(output_image); |
| 27 | memcpy(p_output_image, img.data, img.total() * img.elemSize()); |
| 28 | } |
| 29 | }; |
| 30 | |
| 31 | struct CustomOpImageReader : OrtW::CustomOpBase<CustomOpImageReader, KernelImageReader> { |
| 32 | size_t GetInputTypeCount() const { |
| 33 | return 1; |
| 34 | } |
| 35 | |
| 36 | size_t GetOutputTypeCount() const { |
| 37 | return 1; |
| 38 | } |
| 39 | |
| 40 | ONNXTensorElementDataType GetInputType(size_t index) const { |
| 41 | return ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING; |
| 42 | } |
| 43 | |
| 44 | ONNXTensorElementDataType GetOutputType(size_t index) const { |
| 45 | return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; |
| 46 | } |
| 47 | |
| 48 | const char* GetName() const{ |
| 49 | return "ImageReader"; |
| 50 | } |
| 51 | }; |
| 52 | |