kend0
kend0

Reputation: 11

c++ : "find non zero-elements of cv::mat" not working as intended

I implemented a function which gives you the indices of all non-zero elements of a cv::mat format matrix. I want to identify the white area of this binary image: https://i.sstatic.net/mVJ7N.png . I want to receive the same result as from Matlab's "find" function.My code looks as follows (I hope the experts won't get a heart attack):

#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\core\core.hpp>
#include <opencv2\ml\ml.hpp>
#include <cstring>
#include <iostream>
#include <vector>

using namespace cv;
void findIndex(Mat imgmat, std::vector <std::vector <int> > &indices);

int main(void)
{
String img;
Mat imgmat;
img = "Mask120.png";
imgmat = imread(img);
std::vector <std::vector <int> > indices;
findIndex(imgmat, indices);
return 0;
}


void findIndex(Mat mask, std::vector< std::vector<int> >& indices){
int x_ind[100000]; // ugly, I know
int y_ind[100000];
int k = 0;

for (int i = 0; i < mask.rows; i++) {
    for (int j = 0; j < mask.cols; j++) {
        if (mask.at<uchar>(i, j) == 255) {
            x_ind[k] = j;
            y_ind[k] = i;
            k = k + 1;
        }
    }
}
indices.resize(2, std::vector<int>(k));

for (int m = 0; m < k; m++) {
    indices[0][m] = x_ind[m];
    indices[1][m] = y_ind[m];
}
}

It gives out two vectors as it should, but the results differ to those of Matlab's "find" and are obviously not correct. With find, there are in total around 22000 non-zero elements, this method identifies around 57000. Also, the first index which is marked as non-zero is at i = 119 and j = 561, corresponding to the point (562/120) of my binary image, which is not a white point.

Any ideas on where I have made a mistake is highly appreciated!

Upvotes: 1

Views: 2090

Answers (1)

Vinoj John Hosan
Vinoj John Hosan

Reputation: 6873

I can give a simple solution for your problem

where input cv::Mat is maskMat(it should be CV_8UC1) The output will be updated in locations vector as Points of x and y co-ordinates

Mat whiteMat = maskMat == 255;
vector<Point> locations;
int count = countNonZero(binaryMat);
if(count < 0)
{
    findNonZero(binaryMat,locations);
}

Some higher version of opencv above 3.0

Mat whiteMat = maskMat == 255;
vector<Point> locations;
findNonZero(binaryMat,locations);

Upvotes: 1

Related Questions