image data access in OpenCV 2 or later.

23 Nov

Scrapped from :

Since 2009 with the launch of OpenCV 2, you can count with the new C++ interface, much better than the C style older version. I suggest two ways you can access pixels values. My notes are based on the book OpenCV 2 Computer Vision Application Programming Cookbook, by Robert Laganière.
1. Direct access to pixels values:
     // Test for gray level image
    if (image.channels() == 1) {<uchar>(j, i) = …;           // j runs on rows, i runs on cols
    } else if (image.channels() == 3)   // color image<cv::Vec3b>(j, i)[0] = …;<cv::Vec3b>(j, i)[1] = …;<cv::Vec3b>(j, i)[2] = …;
   The image was created as: cv::Mat image = cv::imread(“img.???”);
2. Scanning image with pointer:
    uchar *pixel;
     cv::Mat image = cv::imread(“img.???”);
     . . .
    for (int j = 0; j < nRow; j++) {
          // Get the address of row j
          pixel = image.ptr<uchar>(j);
          for (int i = 0; i < nCol; i++) {
                // process each pixel
               pixel[i] = …;
choose one method and good job!
1 Comment

Posted by on November 23, 2011 in OpenCV


One response to “image data access in OpenCV 2 or later.

  1. kusemanohar

    April 17, 2013 at 11:59 am

    In the same book there is yet another method to access

    uchar * data =;
    //Gives row-major format on the image
    //After this you can access the data in the same way as we did with opencv1

    This is especially useful if you are doing computation on GPUs


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: