opencv Pixel Access Alternative pixel access with Matiterator


It's not the best way of iterating through the pixels; however, it's better than cv::Mat::at<T>.

Let's assume you have a color image in your folder and you want to iterate each pixels of this image and erase green and red channels(Note that this is an example, you can do this in more optimized ways);

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

int main(int argc, char **argv)

// Create a container
cv::Mat im; 

//Create a vector
cv::Vec3b *vec;

// Create an mat iterator
cv::MatIterator_<cv::Vec3b> it;

// Read the image in color format
im = cv::imread("orig1.jpg", 1);

// iterate through each pixel
for(it = im.begin<cv::Vec3b>(); it != im.end<cv::Vec3b>(); ++it)
    // Erase the green and red channels 
    (*it)[1] = 0;
    (*it)[2] = 0;

// Create a new window
cv::namedWindow("Resulting Image");

// Show the image
cv::imshow("Resulting Image", im);

// Wait for a key

return 0;

To compile this with Cmake:

cmake_minimum_required(VERSION 2.8)
find_package(OpenCV REQUIRED)
add_executable(Main main.cpp)
target_link_libraries(Main ${OpenCV_LIBS})

The original image: enter image description here

The processed image: enter image description here

Note that we don't touch only the Blue channel.

For more information: Page:145