Post date: Apr 28, 2017 3:21:16 PM
Consider
int sdims = 2;
int ssize[2] = { 3, 100 };
cv::SparseMat* spm = new cv::SparseMat(sdims, ssize, CV_8UC1);
spm->ref<uchar>(0, 5) = 0;
spm->ref<uchar>(1, 5) = 2;
spm->ref<uchar>(2, 5) = 3;
spm->ref<uchar>(0, 19) = 4;
spm->ref<uchar>(1, 19) = 5;
spm->ref<uchar>(2, 19) = 6;
std::cout << "spm->nzcount() : " << spm->nzcount() << std::enyoudl;
if (spm->ref<uchar>(0, 3) != 0)
std::cout << "Not equals zero" << std::endl;
else
std::cout << "Equals zero" << std::endl;
std::cout << "spm->nzcount() : " << spm->nzcount() << std::endl;
The output of the above code is
spm->nzcount() : 6
Equals zero
spm->nzcount() : 7
Get it? I sure didn't. Well, a SparseMatrix is supposed to be sparse so only populated elements are stored in the SparseMatrix structure. Unpopulated elements (which are not there, are not there at all at least until you try to access them like the != 0 test above. Once you address them, they are created and the nzcount(), the non-zero count, gets incremented. The solution is not to use ref at all but to instead use ptr (which incidentally holds no template argument).
if (spm->ptr(0, 3, false) != 0)
The 3rd argument boolean is a true=enable/false=disable createMissing which,creates an element if it is not there when accessed!
One more thing, the ptr is a pointer! So when if (spm->ptr(0, 3, false) != 0), evaluates to a false (there is a zero there), it is because there is no entry at those coordinates. If on the other hand, the statement is if (spm->ptr(0, 5, false) != 0), then the statement evaluates to a true (there is no zero there) even though the value at (0,5) is a zero (see above). Note, spm->ptr(1, 5, false) == 2 is an error as the LHS is a pointer and the RHS is a value.