Ask Your Question
3

How to use Mat::forEach position parameter?

asked 2016-11-04 06:01:58 -0600

updated 2016-11-04 06:13:35 -0600

I want to know the pixel id of the Mat element using cv::Mat::forEach position parameter. I read the documentation here and tried the following code!

Code:

typedef cv::Point_<uchar> Pixel;
struct Operator {
    void operator ()(Pixel &pixel, const int * position) const 
    {           
        cout << format("[%d,%d]= %d \n",position[0],position[1],(int)pixel.x);      
    }
};

int main( int argc, char* argv[])
{    
    Mat mTest(Size(3, 2), CV_8UC1,Scalar(0));   
    randn(mTest,Scalar(125),Scalar(125));

    cout<< format (" Size : %d , %d \n",mTest.rows,mTest.cols);

    for (int Rows = 0; Rows < mTest.rows; Rows++)
    {
        for (int Cols = 0; Cols < mTest.cols; Cols++)
        {
            cout << format("[%d,%d]= %d \t",Rows,Cols,mTest.at<uchar>(Rows,Cols));
        }
        cout << "\n";
    }
    cout << "\n\n";

    mTest.forEach<Pixel>(Operator());

    waitKey();

    return 0;
}

Output:

 Size : 2 , 3
[0,0]= 125      [0,1]= 145      [0,2]= 37
[1,0]= 71       [1,1]= 255      [1,2]= 90


[0,0]= 125
[1,0]= 71
[0,1]= 37
[0,2]= 255
[1,1]= 90
[1,2]= 0
Press any key to continue . . .

As you can see there is a mismatch in the Actual Pixel ID and the Position parameter ID! So how to use the position parameter correctly?

Note: I've just noted that there is a different method described in the documentation

i.e forEachWithPosition but it is not available now?

edit retag flag offensive close merge delete

Comments

btw, your docs might be simply outdated.

berak gravatar imageberak ( 2016-11-04 06:26:39 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
3

answered 2016-11-04 06:16:29 -0600

berak gravatar image

for a 1 channel CV_8U image, your Pixel should not be:

typedef cv::Point_<uchar> Pixel; // wrong

but simply:

typedef uchar Pixel;  //  correct

then you'd get:

 Size : 2 , 3
[0,0]= 125      [0,1]= 145      [0,2]= 37
[1,0]= 71       [1,1]= 255      [1,2]= 90


[0,0]= 125
[1,0]= 71
[0,1]= 145
[1,1]= 255
[0,2]= 37
[1,2]= 90
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-11-04 06:01:58 -0600

Seen: 10,991 times

Last updated: Nov 04 '16