Store in Matrix the Row and Column of White pixels

Greetings all, I am quite new to openCV and I was wondering if it would be possible to save in an array (or in some element that is accessible) the position of all the white pixels that have been obtained after performing a binarization with canny to an image.

#include <iostream>
using namespace std;

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

int main(){
    string path = "/path/to/starry_night.jpg";
    Mat img = imread(path,IMREAD_COLOR);
    Mat detectedEdges;
    Canny(img,detectedEdges,150,200);
    imshow("Detected Edges",detectedEdges);

    waitKey(0);
    return 0;
}

UPDATE.
Maybe one solution could be this:

for (int r = 0 ; r < detectedEdges.rows; r++)
    {
        for (int c = 0 ; c < detectedEdges.cols; c++)
        {
            if (detectedEdges.at<uchar>(r,c) == 255)
                cout << r << " " << c << endl;
        }
    }

there isn’t in OpenCV. (edit: there is, see below)

you’d have to write that yourself.

numpy (Python) would have a function.

how would you use such data?

I need to convert the position where these pixels are located to a txt file.

But I’m using c++.
Thanks for you answer. :slight_smile:

take a look at findNonZero

#include <iostream>


#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

int main() {
    string path = samples::findFile("starry_night.jpg");
    Mat img = imread(path, IMREAD_COLOR);
    Mat detectedEdges,idx;
    Canny(img, detectedEdges, 150, 200);
    findNonZero(detectedEdges, idx);
    FileStorage fs("idx.xml", FileStorage::WRITE);
    fs << "cannyresult" << idx;
    imshow("Detected Edges", detectedEdges);

    waitKey(0);
    return 0;
}
2 Likes