microsoft/onnxruntime-extensions
Publicmirrored fromhttps://github.com/microsoft/onnxruntime-extensionsAvailable
operators/vision/impl/image_encoder_decoder.hpp
85lines · modecode
| 1 | #pragma once |
| 2 | |
| 3 | #include <cassert> |
| 4 | #include <cstdint> |
| 5 | #include <string> |
| 6 | #include <vector> |
| 7 | |
| 8 | namespace ort_extensions { |
| 9 | class BaseImageDecoder { |
| 10 | public: |
| 11 | virtual ~BaseImageDecoder() {} |
| 12 | |
| 13 | // HWC |
| 14 | const std::vector<int64_t>& Shape() const { return shape_; } |
| 15 | int64_t NumDecodedBytes() const { return decoded_bytes_; } |
| 16 | |
| 17 | bool Decode(uint8_t* output, uint64_t out_bytes) { |
| 18 | // temporary hack to validate size |
| 19 | assert(shape_.size() == 3 && out_bytes == shape_[0] * shape_[1] * shape_[2]); |
| 20 | return DecodeImpl(output, out_bytes); |
| 21 | } |
| 22 | |
| 23 | protected: |
| 24 | BaseImageDecoder(const uint8_t* bytes, uint64_t num_bytes) |
| 25 | : bytes_{bytes}, num_bytes_{num_bytes} { |
| 26 | } |
| 27 | |
| 28 | const uint8_t* Bytes() const { return bytes_; } |
| 29 | uint64_t NumBytes() const { return num_bytes_; } |
| 30 | |
| 31 | void SetShape(int height, int width, int channels) { |
| 32 | assert(height > 0 && width > 0 && channels == 3); |
| 33 | shape_ = {height, width, channels}; |
| 34 | decoded_bytes_ = height * width * channels; |
| 35 | } |
| 36 | |
| 37 | private: |
| 38 | virtual bool DecodeImpl(uint8_t* output, uint64_t out_bytes) = 0; |
| 39 | |
| 40 | const uint8_t* bytes_; |
| 41 | const uint64_t num_bytes_; |
| 42 | std::vector<int64_t> shape_; |
| 43 | int64_t decoded_bytes_{0}; |
| 44 | }; |
| 45 | |
| 46 | class BaseImageEncoder { |
| 47 | public: |
| 48 | BaseImageEncoder(const uint8_t* bytes, const std::vector<int64_t>& shape) |
| 49 | : bytes_{bytes}, shape_{shape} { |
| 50 | num_bytes_ = 1; |
| 51 | for (auto dim : shape) { |
| 52 | num_bytes_ *= dim; |
| 53 | } |
| 54 | |
| 55 | // avoid re-allocs by assuming worst case of no compression when encoding. |
| 56 | // use resize so we can memcpy to buffer. |
| 57 | encoded_image_.resize(num_bytes_, 0); |
| 58 | } |
| 59 | |
| 60 | const std::vector<int64_t>& Shape() const { return shape_; } |
| 61 | |
| 62 | const std::vector<uint8_t>& Encode() { |
| 63 | bool encoded = EncodeImpl(); |
| 64 | assert(encoded); |
| 65 | return encoded_image_; |
| 66 | } |
| 67 | |
| 68 | virtual ~BaseImageEncoder() {} |
| 69 | |
| 70 | protected: |
| 71 | const uint8_t* Bytes() const { return bytes_; } |
| 72 | uint64_t NumBytes() const { return num_bytes_; } |
| 73 | |
| 74 | std::vector<uint8_t>& Buffer() { return encoded_image_; } |
| 75 | |
| 76 | private: |
| 77 | virtual bool EncodeImpl() = 0; |
| 78 | |
| 79 | const uint8_t* bytes_; |
| 80 | uint64_t num_bytes_; |
| 81 | const std::vector<int64_t> shape_; |
| 82 | |
| 83 | std::vector<uint8_t> encoded_image_; |
| 84 | }; |
| 85 | } // namespace ort_extensions |
| 86 | |