ronantakizawa/codereview-bench huggingface dataset:
Repository: opencv/opencv
File: modules/core/src/persistence.cpp (C++)

Code before:
    if(!p)
        return 0.f;
    int tag = *p;
    int type = (tag & TYPE_MASK);
    p += (tag & NAMED) ? 5 : 1;

    if( type == INT )
    {
        return (double)readInt(p);
    }
    else if( type == REAL )
    {
        return readReal(p);
    }
    else
        return DBL_MAX;
}

double FileNode::real() const  { return double(*this); }
std::string FileNode::string() const
{
    const uchar* p = ptr();
    if( !p || (*p & TYPE_MASK) != STRING )
    {
        if ( (*p & TYPE_MASK) == NONE )
            return std::string("None");
        else
            return std::string();
    }
    p += (*p & NAMED) ? 5 : 1;
    size_t sz = (size_t)(unsigned)readInt(p);
    return std::string((const char*)(p + 4), sz - 1);
}
Mat FileNode::mat() const { Mat value; read(*this, value, Mat()); return value; }

FileNodeIterator FileNode::begin() const { return FileNodeIterator(*this, false); }
FileNodeIterator FileNode::end() const   { return FileNodeIterator(*this, true); }

void FileNode::readRaw( const std::string& fmt, void* vec, size_t len ) const
{
    FileNodeIterator it = begin();
    it.readRaw( fmt, vec, len );
}

size_t FileNode::size() const
{
    const uchar* p = ptr();
    if( !p )
        return 0;
    int tag = *p;
    int tp = tag & TYPE_MASK;

Review comment (suggestion):
At first I think this might be confusing in Python and an empty string is a better chose. However in Python `str(None)` is also a string `"None"`.

Code after:
    if(!p)
        return 0.f;
    int tag = *p;
    int type = (tag & TYPE_MASK);
    p += (tag & NAMED) ? 5 : 1;

    if( type == INT )
    {
        return (double)readInt(p);
    }
    else if( type == REAL )
    {
        return readReal(p);
    }
    else
        return DBL_MAX;
}

double FileNode::real() const  { return double(*this); }
std::string FileNode::string() const
{
    const uchar* p = ptr();
    if( !p || (*p & TYPE_MASK) != STRING )
        return std::string();
    p += (*p & NAMED) ? 5 : 1;
    size_t sz = (size_t)(unsigned)readInt(p);
    return std::string((const char*)(p + 4), sz - 1);
}
Mat FileNode::mat() const { Mat value; read(*this, value, Mat()); return value; }

FileNodeIterator FileNode::begin() const { return FileNodeIterator(*this, false); }
FileNodeIterator FileNode::end() const   { return FileNodeIterator(*this, true); }

void FileNode::readRaw( const std::string& fmt, void* vec, size_t len ) const
{
    FileNodeIterator it = begin();
    it.readRaw( fmt, vec, len );
}

size_t FileNode::size() const
{
    const uchar* p = ptr();
    if( !p )
        return 0;
    int tag = *p;
    int tp = tag & TYPE_MASK;
    if( tp == MAP || tp == SEQ )
    {
        if( tag & NAMED )
            p += 4;
        return (size_t)(unsigned)readInt(p + 5);
Repository: opencv/opencv
File: samples/dnn/alpha_matting.py (Python)

Code before:


def main(func_args=None):
    args = get_args_parser(func_args)
    engine = cv.dnn.ENGINE_AUTO
    if args.backend != "default" or args.target != "cpu":
        engine = cv.dnn.ENGINE_CLASSIC

    image = cv.imread(cv.samples.findFile(args.input))
    if image is None:
        print("Failed to load the input image")
        exit(-1)

    cv.namedWindow("Input", cv.WINDOW_AUTOSIZE)
    cv.namedWindow("Alpha Mask", cv.WINDOW_AUTOSIZE)
    cv.namedWindow("Composite", cv.WINDOW_AUTOSIZE)
    cv.moveWindow("Alpha Mask", 200, 50)
    cv.moveWindow("Composite", 400, 50)

    args.model = findModel(args.model, args.sha1)
    net = loadModel(args, engine)

    inp = cv.dnn.blobFromImage(
        image, args.scale, (args.width, args.height), args.mean, swapRB=args.rgb
    )
    net.setInput(inp)
    alpha_mask, composite = apply_modnet(net, image)

    t, _ = net.getPerfProfile()
    label = "Inference time: %.2f ms" % (t * 1000.0 / cv.getTickFrequency())

    draw_label(image, label, (0, 255, 0))
    draw_label(alpha_mask, label, (255, 255, 255))
    draw_label(composite, label, (0, 255, 0))
    cv.imshow("Input", image)
    cv.imshow("Alpha Mask", alpha_mask)
    cv.imshow("Composite", composite)

    print("Press any key to exit")
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == "__main__":
    main()


Review comment (suggestion):
I wound say, it should be inside of `apply_modnet`

Code after:
    alpha_mask = postprocess_output(image, out)
    alpha_3ch = cv.merge([alpha_mask / 255.0, alpha_mask / 255.0, alpha_mask / 255.0])
    composite = (image.astype(np.float32) * alpha_3ch).astype(np.uint8)
    return alpha_mask, composite


def main(func_args=None):
    args = get_args_parser(func_args)
    engine = cv.dnn.ENGINE_AUTO
    if args.backend != "default" or args.target != "cpu":
        engine = cv.dnn.ENGINE_CLASSIC

    image = cv.imread(cv.samples.findFile(args.input))
    if image is None:
        print("Failed to load the input image")
        exit(-1)

    cv.namedWindow("Input", cv.WINDOW_AUTOSIZE)
    cv.namedWindow("Alpha Mask", cv.WINDOW_AUTOSIZE)
    cv.namedWindow("Composite", cv.WINDOW_AUTOSIZE)
    cv.moveWindow("Alpha Mask", 200, 50)
    cv.moveWindow("Composite", 400, 50)

    args.model = findModel(args.model, args.sha1)
    net = loadModel(args, engine)

    alpha_mask, composite = apply_modnet(args, net, image)

    t, _ = net.getPerfProfile()
    label = "Inference time: %.2f ms" % (t * 1000.0 / cv.getTickFrequency())

    draw_label(image, label, (0, 255, 0))
    draw_label(alpha_mask, label, (255, 255, 255))
    draw_label(composite, label, (0, 255, 0))
    cv.imshow("Input", image)
    cv.imshow("Alpha Mask", alpha_mask)
    cv.imshow("Composite", composite)

    print("Press any key to exit")
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == "__main__":
    main()
Repository: opencv/opencv
File: modules/core/src/cuda_info.cpp (C++)

Code before:
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    return deviceProps().get(device_id_)->canMapHostMemory != 0;
#endif
}

DeviceInfo::ComputeMode cv::cuda::DeviceInfo::computeMode() const
{
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    static const ComputeMode tbl[] =
    {
        ComputeModeDefault,
        ComputeModeExclusive,
        ComputeModeProhibited,
        ComputeModeExclusiveProcess
    };

    int computeMode;
    cudaDeviceGetAttribute(&computeMode, cudaDevAttrComputeMode, device_id_);
    return tbl[computeMode];
#endif
}

int cv::cuda::DeviceInfo::maxTexture1D() const
{
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    size_t maxWidthInElements;
    cudaChannelFormatDesc fmtDesc = cudaCreateChannelDesc<float4>();
    cudaDeviceGetTexture1DLinearMaxWidth(&maxWidthInElements, &fmtDesc, device_id_);
    return maxWidthInElements;
#endif
}

int cv::cuda::DeviceInfo::maxTexture1DMipmap() const
{
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    #if CUDA_VERSION >= 5000
        return deviceProps().get(device_id_)->maxTexture1DMipmap;
    #else
        CV_Error(Error::StsNotImplemented, "This function requires CUDA 5.0");
        return 0;
    #endif
#endif
}

Review comment (suggestion):
`maxTexture1DLinear` has been depreciated not `maxTexture1D`

See

> opencv\modules\core\src\cuda_info.cpp(566): error C2039: 'maxTexture1DLinear': is not a member of 'cudaDeviceProp'

Code after:
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    return deviceProps().get(device_id_)->canMapHostMemory != 0;
#endif
}

DeviceInfo::ComputeMode cv::cuda::DeviceInfo::computeMode() const
{
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    static const ComputeMode tbl[] =
    {
        ComputeModeDefault,
        ComputeModeExclusive,
        ComputeModeProhibited,
        ComputeModeExclusiveProcess
    };

    int computeMode;
    cudaSafeCall(cudaDeviceGetAttribute(&computeMode, cudaDevAttrComputeMode, device_id_));
    return tbl[computeMode];
#endif
}

int cv::cuda::DeviceInfo::maxTexture1D() const
{
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    return deviceProps().get(device_id_)->maxTexture1D;
#endif
}

int cv::cuda::DeviceInfo::maxTexture1DMipmap() const
{
#ifndef HAVE_CUDA
    throw_no_cuda();
#else
    #if CUDA_VERSION >= 5000
        return deviceProps().get(device_id_)->maxTexture1DMipmap;
    #else
        CV_Error(Error::StsNotImplemented, "This function requires CUDA 5.0");
        return 0;
    #endif
#endif
}

int cv::cuda::DeviceInfo::maxTexture1DLinear() const
{
Repository: opencv/opencv
File: modules/dnn/src/layers/size_layer.cpp (C++)

Code before:
        outputs.assign(1, MatShape({1}));
        return false;
    }

    void getTypes(const std::vector<MatType>& /*inputs*/,
                  const int requiredOutputs,
                  const int requiredInternals,
                  std::vector<MatType>& outputs,
                  std::vector<MatType>& internals) const CV_OVERRIDE
    {
        outputs.assign(requiredOutputs, MatType(CV_64S));
        internals.assign(requiredInternals, MatType(CV_64S));
    }

    void forward(InputArrayOfArrays inputs_arr,
                 OutputArrayOfArrays outputs_arr,
                 OutputArrayOfArrays /*internals_arr*/) CV_OVERRIDE
    {
        std::vector<Mat> inputs, outputs;
        inputs_arr.getMatVector(inputs);
        outputs_arr.getMatVector(outputs);

        CV_Assert(inputs.size() == 1);
        const Mat& x = inputs[0];

        size_t total = x.total()*x.channels();

        outputs[0].create(1, 1, CV_64S);
        outputs[0].at<int64_t>(0) = static_cast<int64_t>(total);
    }
};

Ptr<SizeLayer> SizeLayer::create(const LayerParams& params)
{
    return Ptr<SizeLayer>(new SizeLayerImpl(params));
}

}}


Review comment (bug):
That's incorrect for ND cv::Mat. Use `total`: https://github.com/opencv/opencv/blob/649dc297cb6949ad324aa5fcac67dc0456915802/modules/dnn/include/opencv2/dnn/shape_utils.hpp#L155

Code after:
        outputs.assign(1, MatShape({1}));
        return false;
    }

    void getTypes(const std::vector<MatType>& /*inputs*/,
                  const int requiredOutputs,
                  const int requiredInternals,
                  std::vector<MatType>& outputs,
                  std::vector<MatType>& internals) const CV_OVERRIDE
    {
        outputs.assign(requiredOutputs, MatType(CV_64S));
        internals.assign(requiredInternals, MatType(CV_64S));
    }

    void forward(InputArrayOfArrays inputs_arr,
                 OutputArrayOfArrays outputs_arr,
                 OutputArrayOfArrays /*internals_arr*/) CV_OVERRIDE
    {
        std::vector<Mat> inputs, outputs;
        inputs_arr.getMatVector(inputs);
        outputs_arr.getMatVector(outputs);

        CV_Assert(inputs.size() == 1);
        const Mat& x = inputs[0];

        const MatShape xShape = shape(x);
        int64_t totalElems = static_cast<int64_t>(total(xShape));

        outputs[0].create(1, 1, CV_64S);
        outputs[0].at<int64_t>(0) = totalElems;
    }
};

Ptr<SizeLayer> SizeLayer::create(const LayerParams& params)
{
    return Ptr<SizeLayer>(new SizeLayerImpl(params));
}

}}
Repository: opencv/opencv
File: modules/dnn/src/layers/det_layer.cpp (C++)

Code before:
        const size_t matStrideBytes = (size_t)n * (size_t)m * elemSz;

        const uchar* base = X.data;
        uchar* outp = outputs[0].ptr();

        cv::parallel_for_(cv::Range(0, static_cast<int>(batch)), [&](const cv::Range& r){
            for (int bi = r.start; bi < r.end; ++bi)
            {
                size_t b = static_cast<size_t>(bi);
                const uchar* p = base + b * matStrideBytes;
                Mat A(m, n, type, const_cast<uchar*>(p));

                double det = cv::determinant(A);
                if (type == CV_32F)
                    reinterpret_cast<float*>(outp)[b] = static_cast<float>(det);
                else // CV_64F
                    reinterpret_cast<double*>(outp)[b] = det;
            }
        });
    }
};

Ptr<DetLayer> DetLayer::create(const LayerParams& params)
{
    return Ptr<DetLayer>(new DetLayerImpl(params));
}

}}


Review comment (suggestion):
add support for bfloat and hfloat: 1) declare temporary `Mat temp;` outside of `for (int bi = r.start ...)` loop. 2) replace double det = cv::determinant(A); with

```
double det;
if (type == CV_32F || type == CV_64F) {
    det = determinant(A);
} else {
    A.convertTo(temp, CV_32F);
    det = determinant(temp);
}
```
3) add 2 more branches to store determinant to hfloat/bfloat


Code after:
        outputs[0].create(outDims, outSizes.data(), X.type());

        const int type = X.type();
        const size_t elemSz = X.elemSize();
        const size_t matStrideBytes = (size_t)n * (size_t)m * elemSz;

        const uchar* base = X.data;
        uchar* outp = outputs[0].ptr();

        parallel_for_(Range(0, static_cast<int>(batch)), [&](const Range& r){
            Mat temp;
            for (int bi = r.start; bi < r.end; ++bi)
            {
                size_t b = static_cast<size_t>(bi);
                const uchar* p = base + b * matStrideBytes;
                Mat A(m, n, type, const_cast<uchar*>(p));

                double det;
                if (type == CV_32F || type == CV_64F) {
                    det = determinant(A);
                } else {
                    A.convertTo(temp, CV_32F);
                    det = determinant(temp);
                }

                if (type == CV_32F)
                    reinterpret_cast<float*>(outp)[b] = static_cast<float>(det);
                else if (type == CV_64F)
                    reinterpret_cast<double*>(outp)[b] = det;
                else if (type == CV_16F)
                    reinterpret_cast<hfloat*>(outp)[b] = saturate_cast<hfloat>(det);
                else if (type == CV_16BF)
                    reinterpret_cast<bfloat*>(outp)[b] = saturate_cast<bfloat>(det);
                else
                    CV_Error(Error::BadDepth, "Unsupported input/output depth for DetLayer");
            }
        });
    }
};

Ptr<DetLayer> DetLayer::create(const LayerParams& params)
{
    return Ptr<DetLayer>(new DetLayerImpl(params));
}

}}
Repository: opencv/opencv
File: modules/dnn/src/layers/bitshift_layer.cpp (C++)

Code before:
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Copyright (C) 2025, BigVision LLC, all rights reserved.
// Third party copyrights are property of their respective owners.

#include "../precomp.hpp"
#include "layers_common.hpp"

// ONNX reference: BitShift operator
// Spec: https://onnx.ai/onnx/operators/onnx__BitShift.html
// Supported opsets: ai.onnx opset 11 and newer

namespace cv {
namespace dnn {

template<typename T, typename U>
static inline T doShift(T inputVal, U shiftVal, int direction, int bitWidth)
{
    return (uint64_t)shiftVal >= (uint64_t)bitWidth
           ? T(0)
           : T(direction ? (inputVal >> (U)shiftVal) : (inputVal << (U)shiftVal));
}

template<typename T, int CvTypeConst, int BitWidth>
void runBitShift(const Mat& input, const Mat& shift, Mat& output, int direction)
{
    output.create(input.dims, input.size.p, input.type());
    const size_t numElements = input.total();

    const T* inputPtr = input.ptr<T>();
    T* outputPtr = output.ptr<T>();

    if (shift.total() == 1)
    {
        T shiftScalar = 0;
        tensorToScalar(shift, CvTypeConst, &shiftScalar);

Review comment (suggestion):
please, put a note here that broadcasting is not fully supported, only the same shapes (`array shift array`) or `array shift scalar`

Code after:
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Copyright (C) 2025, BigVision LLC, all rights reserved.
// Third party copyrights are property of their respective owners.

#include "../precomp.hpp"
#include "layers_common.hpp"

// ONNX reference: BitShift operator
// Spec: https://onnx.ai/onnx/operators/onnx__BitShift.html
// Supported opsets: ai.onnx opset 11 and newer
// NOTE: Broadcasting is NOT fully supported. Only two cases are handled:
// 1) array (input[0]) shifted by array (input[1]) of the SAME SHAPE
// 2) array (input[0]) shifted by a SCALAR (0-D) shift amount

namespace cv {
namespace dnn {

template<typename T, typename U>
static inline T doShift(T inputVal, U shiftVal, int direction, int bitWidth)
{
    return (uint64_t)shiftVal >= (uint64_t)bitWidth
           ? T(0)
           : T(direction ? (inputVal >> shiftVal) : (inputVal << shiftVal));
}

template<typename T, int CvTypeConst, int BitWidth>
void runBitShift(const Mat& input, const Mat& shift, Mat& output, int direction)
{
    output.create(input.dims, input.size.p, input.type());
    const size_t numElements = input.total();

    const T* inputPtr = input.ptr<T>();
    T* outputPtr = output.ptr<T>();

    if (shift.total() == 1)
Repository: opencv/opencv
File: samples/dnn/auto_white_balance.py (Python)

Code before:
    try:
        net = cv.dnn.readNetFromONNX(args.model)
        net.setPreferableBackend(get_backend_id(args.backend))
        net.setPreferableTarget(get_target_id(args.target))
    except cv.error as e:
        print(f"Error loading model: {e}", file=sys.stderr)
        sys.exit(1)

    img = cv.imread(findFile(args.input), cv.IMREAD_COLOR)
    if img is None:
        print(f"Cannot load image: {args.input}", file=sys.stderr)
        sys.exit(1)

    blob = cv.dnn.blobFromImage(
        img, scalefactor=args.scale, size=(img.shape[1], img.shape[0]),
        mean=args.mean, swapRB=args.rgb, crop=False, ddepth=cv.CV_32F
    )
    net.setInput(blob)

    try:
        out = net.forward()
    except cv.error as e:
        print(f"Forward error: {e}", file=sys.stderr)
        sys.exit(1)

    illum = out.astype(np.float32).reshape(-1)[:3]
    corrected = correct(img, illum)

    orig_vis = img.copy()
    corr_vis = corrected.copy()
    annotate(orig_vis, "Original")
    annotate(corr_vis, "FC4-corrected")
    stacked = np.hstack([orig_vis, corr_vis])
    cv.imshow("Original and Corrected Images", stacked)
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == "__main__":
    main()


Review comment (suggestion):
Add check for out shape: 
```
if out.size < 3: 
print(error) 
sys.exit(-1)
```

Code after:

    try:
        net = cv.dnn.readNetFromONNX(args.model)
        net.setPreferableBackend(get_backend_id(args.backend))
        net.setPreferableTarget(get_target_id(args.target))
    except cv.error as e:
        print(f"Error loading model: {e}", file=sys.stderr)
        sys.exit(1)

    img = cv.imread(findFile(args.input), cv.IMREAD_COLOR)
    if img is None:
        print(f"Cannot load image: {args.input}", file=sys.stderr)
        sys.exit(1)

    blob = cv.dnn.blobFromImage(
        img, scalefactor=args.scale, size=(img.shape[1], img.shape[0]),
        mean=args.mean, swapRB=args.rgb, crop=False, ddepth=cv.CV_32F
    )
    net.setInput(blob)

    try:
        out = net.forward()
    except cv.error as e:
        print(f"Forward error: {e}", file=sys.stderr)
        sys.exit(1)

    illum = out.astype(np.float32).reshape(-1)
    if out.size != 3:
        print("Error: model output of size not equal to 3 (should output 3 illuminants in RGB order)")
        sys.exit(-1)

    corrected = correct(img, illum)

    orig_vis = img.copy()
    corr_vis = corrected.copy()
    annotate(orig_vis, "Original")
    annotate(corr_vis, "FC4-corrected")
    stacked = np.hstack([orig_vis, corr_vis])
    cv.imshow("Original and Corrected Images", stacked)
    cv.waitKey(0)
    cv.destroyAllWindows()


if __name__ == "__main__":
    main()
Repository: opencv/opencv
File: modules/dnn/include/opencv2/dnn/all_layers.hpp (C++)

Code before:

    class CV_EXPORTS SizeLayer : public Layer
    {
    public:
        static Ptr<SizeLayer> create(const LayerParams &params);
    };

    class CV_EXPORTS DetLayer : public Layer
    {
    public:
        static Ptr<DetLayer> create(const LayerParams &params);
    };

    class CV_EXPORTS CenterCropPadLayer : public Layer
    {
    public:
        static Ptr<CenterCropPadLayer> create(const LayerParams& params);
    };

    class CV_EXPORTS DFTLayer : public Layer
    {
    public:
        bool inverse;
        bool onesided;
        int axis_attr;
        int dft_length;
        std::vector<int> axes;
        static Ptr<DFTLayer> create(const LayerParams &params);
    };

    class CV_EXPORTS Resize2Layer : public Layer
    {
    public:
        static Ptr<Resize2Layer> create(const LayerParams& params);
    };

    // Shared reduction enum for DNN loss layers
    enum LossReduction
    {
        LOSS_REDUCTION_NONE = 0,
        LOSS_REDUCTION_MEAN = 1,
        LOSS_REDUCTION_SUM = 2
    };

    class CV_EXPORTS NegativeLogLikelihoodLossLayer : public Layer
    {
    public:
        LossReduction reduction;
        int ignoreIndex;

        static Ptr<NegativeLogLikelihoodLossLayer> create(const LayerParams& params);

Review comment (suggestion):
please, remove dft_length from attributes, because it's input, not an attribute. Compute dft_length only inside getMemoryShapes (if the second input is constant) and inside forward. Otherwise, the logic becomes quite fuzzy.

Code after:

    class CV_EXPORTS SizeLayer : public Layer
    {
    public:
        static Ptr<SizeLayer> create(const LayerParams &params);
    };

    class CV_EXPORTS DetLayer : public Layer
    {
    public:
        static Ptr<DetLayer> create(const LayerParams &params);
    };

    class CV_EXPORTS CenterCropPadLayer : public Layer
    {
    public:
        static Ptr<CenterCropPadLayer> create(const LayerParams& params);
    };

    class CV_EXPORTS DFTLayer : public Layer
    {
    public:
        bool inverse;
        bool onesided;
        int axis_attr;
        std::vector<int> axes;
        static Ptr<DFTLayer> create(const LayerParams &params);
    };

    class CV_EXPORTS Resize2Layer : public Layer
    {
    public:
        static Ptr<Resize2Layer> create(const LayerParams& params);
    };

    // Shared reduction enum for DNN loss layers
    enum LossReduction
    {
        LOSS_REDUCTION_NONE = 0,
        LOSS_REDUCTION_MEAN = 1,
        LOSS_REDUCTION_SUM = 2
    };

    class CV_EXPORTS NegativeLogLikelihoodLossLayer : public Layer
    {
    public:
        LossReduction reduction;
        int ignoreIndex;

        static Ptr<NegativeLogLikelihoodLossLayer> create(const LayerParams& params);
    };