OpenCV: Find all non-zero coordinates of a binary Mat image

Here is an explanation for how findNonZero() saves non-zero elements. The following codes should be useful to access non-zero coordinates of your binary image. Method 1 used findNonZero() in OpenCV, and Method 2 checked every pixels to find the non-zero (positive) ones.

Method 1:

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
    Mat img = imread("binary image");
    Mat nonZeroCoordinates;
    findNonZero(img, nonZeroCoordinates);
    for (int i = 0; i < nonZeroCoordinates.total(); i++ ) {
        cout << "Zero#" << i << ": " << nonZeroCoordinates.at<Point>(i).x << ", " << nonZeroCoordinates.at<Point>(i).y << endl;
    }
    return 0;
}

Method 2:

#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;

int main(int argc, char** argv) {
    Mat img = imread("binary image");
    for (int i = 0; i < img.cols; i++ ) {
        for (int j = 0; j < img.rows; j++) {
            if (img.at<uchar>(j, i) > 0) {  
                cout << i << ", " << j << endl;     // Do your operations
            }
        }
    }
    return 0;
}

Leave a Comment