Computer Vision Set: OpenCV programming Slides by D.A. Forsyth, C.F. Olson, J. Ponce, L.G. Shapiro More programming in OpenCV
Accessing pixels The most general way to access pixels is a template method: image.at (row, col) This returns a reference, so it can be an lvalue or an rvalue. For color images, we need to say which channel: image.at (row, col)[channel]// channel is 0,1,2 Note that channel 0 is blue, channel 1 is green, channel 2 is red. Computer Vision Set: OpenCV programming Slides by D.A. Forsyth, C.F. Olson, J. Ponce, L.G. Shapiro
Accessing pixels Creating the image with a specific type allows shorter code. Mat_ greyImage = imread(“grey.jpg”); uchar greylevel = greyImage(row, col); Mat_ colorImage = imread(“color.jpg”); colorImage(row, col)[0] = newBlueValue; Computer Vision Set: OpenCV programming Slides by D.A. Forsyth, C.F. Olson, J. Ponce, L.G. Shapiro
Accessing pixels Pixels can also be accessed using pointer manipulation. This is the fastest, but not necessarily the best. int perRow = image.cols * image.channels(); for (int r = 0; r < image.rows; r ++) { uchar *currentRow = image.ptr (r); // ok for grey or color for (int c = 0; c < perRow; c++) { currentRow[c] = 255 – currentRow[c]; // invert pixel color } Computer Vision Set: OpenCV programming Slides by D.A. Forsyth, C.F. Olson, J. Ponce, L.G. Shapiro
Accessing pixels A couple of notes: Acquiring a new pointer for each row is generally necessary, since the rows may be padded. uchar *currentRow = image.ptr (r); // ok for grey or color Can also use pointer arithmetic: * currentRow++ = 255 – *currentRow; // invert pixel color Computer Vision Set: OpenCV programming Slides by D.A. Forsyth, C.F. Olson, J. Ponce, L.G. Shapiro
Accessing pixels One more to access the pixels is using iterators. This will give you all of the pixels in raster order. Mat_ ::iterator it = image.begin (); Mat_ ::iterator itend = image.end (); for ( ; it != itend; ++it) for (int c = 0; c < 3; c++) (*it)[c] = (*it)[c]; Computer Vision Set: OpenCV programming Slides by D.A. Forsyth, C.F. Olson, J. Ponce, L.G. Shapiro