// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/common/common.h" #include "core/common/narrow.h" #include "core/common/safeint.h" #include "core/framework/op_kernel.h" #include "core/util/math_cpuonly.h" namespace onnxruntime { namespace contrib { template class ImageScaler final : public OpKernel { public: ImageScaler(const OpKernelInfo& info) : OpKernel(info) { ORT_THROW_IF_ERROR(info.GetAttr("scale", &scale_)); ORT_THROW_IF_ERROR(info.GetAttrs("bias", bias_)); } Status Compute(OpKernelContext* context) const override { const Tensor* X = context->Input(0); if (X == nullptr) return Status(common::ONNXRUNTIME, common::FAIL, "input count mismatch"); const auto& dims = X->Shape().GetDims(); if (dims.size() < 4) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Input is expected to have four dimensions corresponding to [N,C,H,W], got ", dims.size()); } const int64_t N = dims[0]; const int64_t C = dims[1]; const int64_t H = dims[2]; const int64_t W = dims[3]; // The loop below reads bias_[nc % C] for every channel, so the bias must have exactly one entry // per channel. An empty bias is not a valid "no bias" state here: the constructor already fails // when the attribute is absent, and a present-but-empty attribute would otherwise index an // empty vector. if (bias_.size() != static_cast(C)) { return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "Bias size (", bias_.size(), ") does not match the number of channels (", C, ")"); } Tensor* Y = context->Output(0, TensorShape({N, C, H, W})); ConstEigenArrayMap X_arr(X->Data(), SafeInt(H) * W, SafeInt(N) * C); EigenArrayMap Y_arr(Y->MutableData(), SafeInt(H) * W, SafeInt(N) * C); for (int64_t nc = 0; nc < N * C; ++nc) { Y_arr.col(narrow(nc)) = scale_ * X_arr.col(narrow(nc)) + bias_[narrow(nc % C)]; } return Status::OK(); } protected: float scale_; std::vector bias_; }; } // namespace contrib } // namespace onnxruntime