From IPLImage to Mat

I am very familiar with the IPL image format used in OpenCV 1.1. However, I am using the latest version 2.4 and want to switch to the C ++ OpenCV interface. Here is the way I access image pixels:

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 converting this exact code block with a Mat structure. I find several functions here and there, but it will be very useful if I get the exact conversion of several lines as a whole.

+6
source share
2 answers
 // 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; } } 
+8
source

First, you can perform the same operation in IPLImage and use the built-in Mat constructor to convert it.

Secondly, your code seems too complicated since you are doing the same operation for all three dimensions. The following are more neat (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 levels 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; } 
+3
source

Source: https://habr.com/ru/post/944460/


All Articles