60 likes | 236 Views
Lecture 3 More programming in OpenCV. Slides by: Clark F. Olson. Accessing pixels. The most general way to access pixels is a template method: image.at< uchar >(row, col) This returns a reference, so it can be an lvalue or an rvalue . For color images, we need to say which channel:
E N D
Lecture 3More programming in OpenCV Slides by: Clark F. Olson
Accessing pixels The most general way to access pixels is a template method: image.at<uchar>(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<Vec3b>(row, col)[channel] // channel is 0,1,2 Note that channel 0 is blue, channel 1 is green, channel 2 is red.
Accessing pixels Creating the image with a specific type allows shorter code. Mat_<uchar> greyImage = imread(“grey.jpg”); uchargreylevel = greyImage(row, col); Mat_<Vec3b> colorImage = imread(“color.jpg”); colorImage(row, col)[0] = newBlueValue;
Accessing pixels Pixels can also be accessed using pointer manipulation. This is the fastest, but not necessarily the best. intperRow = image.cols * image.channels(); for (int r = 0; r < image.rows; r ++) { uchar *currentRow = image.ptr<uchar>(r); // ok for grey or color for (int c = 0; c < perRow; c++) { currentRow[c] = 255 – currentRow[c]; // invert pixel color } }
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<uchar>(r); // ok for grey or color • Can also use pointer arithmetic: *currentRow++ = 255 – *currentRow; // invert pixel color
Accessing pixels One more way to access the pixels is using iterators. This will give you all of the pixels in raster order. Mat_<Vec3b>::iterator it = image.begin<Vec3b>(); Mat_<Vec3b>::iterator itend = image.end<Vec3b>(); for ( ; it != itend; ++it) for (int c = 0; c < 3; c++) (*it)[c] = 256 - (*it)[c];