LUT for different channels in C ++, opencv2

I have been playing with opencv2 implemented in C ++ for several days and have noticed that lookup tables are the fastest way to apply changes to an image. However, I had some problems using them for my purposes.

The code below shows an example of inverting pixel values:

bool apply(Image& img) {
   int dim(256);
   Mat lut(1, &dim, CV_8U);
   for (int i=0; i<256; i++)
      lut.at<uchar>(i)= 255-i;
   LUT(img.final,lut,img.final);
   return true;
}

class Image {
public:
   const Mat& original;
   Mat final;
...
};

Since it is very efficient, much more efficient than changing each pixel by one (verified by my own tests), I would like to use this method for other operations. However, for this I have to access each layer (each color, image in BGR) separately. For example, I would like to change blue to 255-i, green to 255-i / 2 and red to 255-i / 3.

, . , (documentation), .

+5
1

:

( ) ,

, LUT:

bool apply(Image& img) {
   int dim(256);

   Mat lut(1, &dim, CV_8UC(img.final.channels()));

   if( img.final.channels() == 1)
   {
      for (int i=0; i<256; i++)
         lut.at<uchar>(i)= 255-i;
   }
   else // stupid idea that all the images are either mono either multichannel
   {
      for (int i=0; i<256; i++)
      {
         lut.at<Vec3b>(i)[0]= 255-i;   // first channel  (B)
         lut.at<Vec3b>(i)[1]= 255-i/2; // second channel (G)
         lut.at<Vec3b>(i)[2]= 255-i/3; // ...            (R)
      }
   }

   LUT(img.final,lut,img.final); // are you sure you are doing final->final? 
   // if yes, correct the LUT allocation part

   return true;
}
+5

All Articles