Reputation: 445
I am well acquainted with the IPL-image format used in OpenCV 1.1. However i am using the latest 2.4 version and want to switch to the C++ interface of OpenCV. Here is the method by which i access the pixels in an image:
int step = img->widthStep;
int height = img->height;
int width = img->width;
unsigned char* data = (unsigned char*) img->imageData;
for (int i=0; i<height; i++)
{
for (int j=0; j<step; j+=3) // 3 is the number of channels.
{
if (data[i*step + j] > 200) // For blue
data[i*step + j] = 255;
if (data[i*step + j + 1] > 200) // For green
data[i*step + j + 1] = 255;
if (data[i*step + j + 2] > 200) // For red
data[i*step + j + 2] = 255;
}
}
I need help for converting this exact code block with the Mat structure. I find several functions here and there but it will be very helpful if i get the exact conversion of the above few lines as a whole.
Upvotes: 6
Views: 1931
Reputation: 1532
First, you can do the same operation on IPLImage and using the built-in constructor of Mat to convert it.
Secondly, your code seems to be overly complicated, as you're doing the same operation for all 3 dimensions. The following is tidier (in Mat notation):
unsigned char* data = (unsigned char*) img.data;
for (int i = 0; i < image.cols * image.rows * image.channels(); ++i) {
if (*data > 200) *data = 255;
++data;
}
If you want the thres for the channels to be different, then:
unsigned char* data = (unsigned char*) img.data;
assert(image.channels() == 3);
for (int i = 0; i < image.cols * image.rows; ++i) {
if (*data > 200) *data = 255;
++data;
if (*data > 201) *data = 255;
++data;
if (*data > 202) *data = 255;
++data;
}
Upvotes: 3
Reputation: 39796
// Mat mat; // a bgr, CV_8UC3 mat
for (int i=0; i<mat.rows; i++)
{
// get a new pointer per row. this replaces fumbling with widthstep, etc.
// also a pointer to a Vec3b pixel, so no need for channel offset, either
Vec3b *pix = mat.ptr<Vec3b>(i);
for (int j=0; j<mat.cols; j++)
{
Vec3b & p = pix[j];
if ( p[0] > 200 ) p[0] = 255;
if ( p[1] > 200 ) p[1] = 255;
if ( p[2] > 200 ) p[2] = 255;
}
}
Upvotes: 8