Exception when executing ONNX model

I have a neural net model stored in a ONNX file. I can load it without issue using model = readNetFromONNX(path);. However, I get an exception when calling model.forward().

The exception is a failed assertion in the static function total found in shape_utils.hpp:

CV_Assert(start <= (int)shape.size() && end <= (int)shape.size() && start <= end);

What happens is that start is 1, end is 6, and shape.size() is 5. The condition that fails is end <= (int)shape.size(). Clearly 6 is not less than or equal to 5.

Here is the code for total. shape is a zero based array. It isn’t clear to me why total is called with end greater than shape.size(). The ONNX file is read without any issue using Netron.

static inline int total(const MatShape& shape, int start = -1, int end = -1)
{
if (start == -1) start = 0;
if (end == -1) end = (int)shape.size();

if (shape.empty())
    return 0;

int elems = 1;
CV_Assert(start <= (int)shape.size() && end <= (int)shape.size() &&
          start <= end);
for(int i = start; i < end; i++)
{
    elems *= shape[i];
}
return elems;

}

UPDATE

I was using an export script that comes with YOLOv5 from Ultralytics to create the ONNX file. I just cloned the latest version of YOLOv5 from git. Problem went away.

On the bright side I did learn a lot by building a debug version of OpenCV and stepping through the code :relaxed:

1 Like