#include <opencv2\opencv.hpp>
using namespace cv;
/**Example that shows how to access an image with three channels using OpenCV version 2.
*/
int main()
{
// Pretend Mat is an image in HSV color space
Mat hsv( 512, 512, CV_8UC3 );
// Row-wise
for( int r = 0; r < hsv.rows; ++r )
{
// Pointer to beginning of current row
unsigned char *row = hsv.ptr( r );
// Column-wise
for( int c = 0; c < hsv.cols; ++c )
{
/*
In order to access a certain channel of a certain pixel
multiply column's index by count of channels and
add channel's index as offset. The following sketch shows
a 1x3 image with 3 channels:
---------------------------------------------------
channel | 0 : 1 : 2 | 0 : 1 : 2 | 0 : 1 : 2 |
(e.g.) | h : s : v | h : s : v | h : s : v |
(e.g.) | b : g : r | b : g : r | b : g : r |
--------------------------------------------------- . . .
column | 0 | 1 | 2 |
---------------------------------------------------
*/
// More or less random values (unintentionally chosen)
row[3*c] = 0; // hue :: blue in BGR color space
row[3*c+1] = r/2; // saturation :: green in BGR color space
row[3*c+2] = c/2; // value :: red in BGR color space
}
}
// Save Mat as image
// Note that images HSV color space will be stored as they were in BGR color space
// so colors might be confusing people unfamiliar with HSV color space
imwrite ( "X:\\hsv.png", hsv );
// Save as an image in BGR color space
Mat bgr;
cvtColor( hsv, bgr, CV_HSV2BGR ); // convert to BGR color space
imwrite ( "X:\\bgr.png", bgr );
return 0;
}