Write big OpenCv Mat

Write big OpenCv Mat

本文关键字:Mat OpenCv big Write      更新时间:2023-10-16

我正试图将OpenCV Mat格式的大浮点矩阵写入二进制文件。我在Linux x64的虚拟机上。

并且我在计数器536000000周围粉碎,所以似乎我在p+ I *4的"可疑行"周围有int溢出?(顺便说一下,assert没有检测到这种情况,为什么?)。

所以当我把"int I"改为"int64 I"时,一切似乎都很好,但我不确定添加超过2^32的char*指针是否安全?

另外,OpenCV矩阵的最大大小是多少?

    bool WriteFloatMat(string path, const Mat &img)
    {
        ofstream fs(path, ios::binary);
        fs.write( (char*)&(img.cols), 4);
        fs.write( (char*)&(img.rows), 4);
        int64 sz_ = img.cols*img.rows;//
        assert(sz_ < numeric_limits<int>::max());//
        int sz = img.cols*img.rows;
        cout << sz << endl;
        int64 counter=0;
        int64 maxVal= numeric_limits<int>::max();
        char* p= image.ptr<char>();
        for(int i=0; i<sz; ++i)
        {
            assert(i*4 < numeric_limits<int>::max());//suspicious line
            fs.write( p+i*4, 4);
            ++counter;
            if(counter%1000000==0)
                cout << counter << endl;
            if(counter>maxVal)
                cout << "Out of limits!" << endl;
        }
        return true;
    }

void TestIO()
{
    //max matrix dimensions?
    int rows= 1000*1000*10;
    int cols= 100;
    Mat mat(rows,cols,CV_32FC1);
    mat=mat+7;
    double t = (double)getTickCount();
    WriteFloatMat("/media/dummy.big", mat);
    t = ((double)getTickCount() - t)/getTickFrequency();
    cout << "Times passed in seconds: " << t << endl;
}

更新:我理解为什么assert(i*4 < numeric_limits<int>::max());不工作,因为I *4溢出和<0所以assert(i*4 >=0 );工作。

OpenCV对图像的大小没有内部限制,它实际上是将其视为内存块。因此,限制将与您正在使用的c++系统有关。

对于它的价值,我发现boost数字库中的numeric_cast<>功能非常有助于捕获转换错误,例如您遇到的assert(i*4 < numeric_limits<int>::max())。(当然,这个问题很微妙,所以它可能也没有帮助。)