pub struct SparseMat { /* private fields */ }
Expand description

The class SparseMat represents multi-dimensional sparse numerical arrays.

Such a sparse array can store elements of any type that Mat can store. Sparse means that only non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its stored elements can actually become 0. It is up to you to detect such elements and delete them using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is filled so that the search time is O(1) in average (regardless of whether element is there or not). Elements can be accessed using the following methods:

  • Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and SparseMat::find), for example:
    const int dims = 5;
    int size[5] = {10, 10, 10, 10, 10};
    SparseMat sparse_mat(dims, size, CV_32F);
    for(int i = 0; i < 1000; i++)
    {
        int idx[dims];
        for(int k = 0; k < dims; k++)
            idx[k] = rand() % size[k];
        sparse_mat.ref<float>(idx) += 1.f;
    }
    cout << "nnz = " << sparse_mat.nzcount() << endl;
  • Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. That is, the iteration loop is familiar to STL users:
    // prints elements of a sparse floating-point matrix
    // and the sum of elements.
    SparseMatConstIterator_<float>
        it = sparse_mat.begin<float>(),
        it_end = sparse_mat.end<float>();
    double s = 0;
    int dims = sparse_mat.dims();
    for(; it != it_end; ++it)
    {
        // print element indices and the element value
        const SparseMat::Node* n = it.node();
        printf("(");
        for(int i = 0; i < dims; i++)
            printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")");
        printf(": %g\n", it.value<float>());
        s += *it;
    }
    printf("Element sum is %g\n", s);

If you run this loop, you will notice that elements are not enumerated in a logical order (lexicographical, and so on). They come in the same order as they are stored in the hash table (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. Note, however, that pointers to the nodes may become invalid when you add more elements to the matrix. This may happen due to possible buffer reallocation.

  • Combination of the above 2 methods when you need to process 2 or more sparse matrices simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 floating-point sparse matrices:
    double cross_corr(const SparseMat& a, const SparseMat& b)
    {
        const SparseMat *_a = &a, *_b = &b;
        // if b contains less elements than a,
        // it is faster to iterate through b
        if(_a->nzcount() > _b->nzcount())
            std::swap(_a, _b);
        SparseMatConstIterator_<float> it = _a->begin<float>(),
                                        it_end = _a->end<float>();
        double ccorr = 0;
        for(; it != it_end; ++it)
        {
            // take the next element from the first matrix
            float avalue = *it;
            const Node* anode = it.node();
            // and try to find an element with the same index in the second matrix.
            // since the hash value depends only on the element index,
            // reuse the hash value stored in the node
            float bvalue = _b->value<float>(anode->idx,&anode->hashval);
            ccorr += avalue*bvalue;
        }
        return ccorr;
    }

Implementations

Various SparseMat constructors.

Various SparseMat constructors.

Overloaded parameters
Parameters
  • dims: Array dimensionality.
  • _sizes: Sparce matrix size on all dementions.
  • _type: Sparse matrix data type.

Various SparseMat constructors.

Overloaded parameters
Parameters
  • m: Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted to sparse representation.

Various SparseMat constructors.

Overloaded parameters
Parameters
  • m: Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted to sparse representation.

Trait Implementations

Wrap the specified raw pointer Read more
Return an the underlying raw pointer while consuming this wrapper. Read more
Return the underlying raw pointer. Read more
Return the underlying mutable raw pointer Read more

Calls try_clone() and panics if that fails

Performs copy-assignment from source. Read more
Executes the destructor for this type. Read more
reallocates sparse matrix. Read more
sets all the sparse matrix elements to 0, which means clearing the hash table.
manually increments the reference counter to the header.
specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. return pointer to the matrix element. - if the element is there (it’s non-zero), the pointer to it is returned - if it’s not there and createMissing=false, NULL pointer is returned - if it’s not there and createMissing=true, then the new element is 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. Read more
returns pointer to the specified element (2D case) Read more
returns pointer to the specified element (3D case) Read more
returns pointer to the specified element (nD case) Read more
erases the specified element (2D case) Read more
erases the specified element (3D case) Read more
erases the specified element (nD case) Read more
return the sparse matrix iterator pointing to the first sparse matrix element Read more
return the sparse matrix iterator pointing to the element following the last sparse matrix element Read more
/////////// some internal-use methods ///////////////
creates full copy of the matrix
copies all the data to the destination matrix. All the previous content of m is erased
converts sparse matrix to dense matrix.
multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type Read more
converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. Read more
C++ default parameters Read more
returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements)
returns elemSize()/channels()
returns type of sparse matrix elements
returns the depth of sparse matrix elements
returns the number of channels
returns the array of sizes, or NULL if the matrix is not allocated
returns the size of i-th matrix dimension (or 0)
returns the matrix dimensionality
returns the number of non-zero elements (=the number of hash table nodes)
computes the element hash value (1D case)
computes the element hash value (2D case)
computes the element hash value (3D case)
computes the element hash value (nD case)
returns the read-only sparse matrix iterator at the matrix beginning
returns the read-only sparse matrix iterator at the matrix end

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.