Search code examples
c++opencvsparse-matrix

OpenCV: how to check if element exists in SparseMat


I am using a SparseMat of CV_32FC3 and am trying to do the following:

int dims = 2;
    int size[] = {10,10};
    SparseMat m = SparseMat(dims, size, CV_32FC3);
    m.ref<Vec3f>(2,5)[0] = 0.5;
    m.ref<Vec3f>(2,5)[0] = 0.5;
    m.ref<Vec3f>(2,5)[0] = 0.5;

    if(m.find(2,6) == m.end()){
        cout << " could not find 2,6" << endl;
    }
    if(m.find(2,5) != m.end()){
        cout << "found 2, 5" << m.ref<Vec3f>(2,5)[0] << ", " << .ref<Vec3f>(2,5)[1] << ", " << .ref<Vec3f>(2,5)[2] << endl;
    }

However, the find part is incorrect, how do I use this to check if an element at that index has been added to the sparse mat?

Thanks


Solution

  • From the definition of SparseMat::ptr:

    C++: uchar* SparseMat::ptr(int i0, int i1, bool createMissing, size_t* hashval=0)
    

    Return pointer to the matrix element. If the element is there (it is non-zero), the pointer to it is returned. If it is not there and createMissing=false, NULL pointer is returned. If it is not there and createMissing=true, the new elementis created and initialized with 0. Pointer to it is returned. If the optional hashval pointer is not NULL, the element hash value is not computed but hashval is taken instead.

    So in your code

    m.find(2,6) == m.end()
    m.find(2,5) != m.end()
    

    should be

    m.ptr(2,6,false) == NULL
    m.ptr(2,5,false) != NULL