OpenCV LUT(look up table) example code

OpenCV LUT example source code


...
int LUTexample()
{

    Mat img = imread("AbyssCGI2.jpg");

    Mat lookUpTable(1, 256, CV_8U);
    uchar* p = lookUpTable.data;
    int factor = 256 / 5;
    for (int i = 0; i < 256; ++i)
    {
        p[i] = factor * (i / factor);
        printf("[%d] = %d \n", i, p[i]);
    }



    Mat reduced;
    LUT(img, lookUpTable, reduced);

    namedWindow("img", 0);
    imshow("img", img);
    namedWindow("reduced", 0);
    imshow("reduced", reduced);


    /*
    //////////////////// gray & color test!!
    Mat img2(1, 1, CV_8UC3);
    img2.setTo(Scalar(0, 128, 255));
    Mat im_color3;
    LUT(img2, lookUpTable, im_color3);
    cout << im_color3 << endl;
    //namedWindow("im_color3", 0);
    //imshow("im_color3", im_color3);

    //different result with color!!
    Mat img2_gray;
    cvtColor(img2, img2_gray, CV_BGR2GRAY);
    Mat im_color4;
    LUT(img2_gray, lookUpTable, im_color4);
    cout << im_color4 << endl;
    //namedWindow("im_color4", 0);
    //imshow("im_color4", im_color4);
    //////////////////////*/


    waitKey(0);


    return 0;

}
...



Loop & LUT processing time compare

 Loop & LUT processing time compare


...
#include "opencv2/opencv.hpp"
#include "opencv2/cuda.hpp"
#include "opencv2\cudaarithm.hpp"
#include <iostream>
#include <time.h>

using namespace std;
using namespace cv;

int main(int, char)
{
    unsigned long AAtime = 0, BBtime = 0;
    unsigned char O[1000][1000] = { 1, 2, };

    //very slow;
    AAtime = getTickCount();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            int t = O[i][j] * 1.14;
            t = (t > 255) ? 255 : t;
            O[i][j] = t;
        }
    }
    BBtime = getTickCount();
    printf("just loop %.5lf sec \n", (BBtime - AAtime) / getTickFrequency()); //chec
    
    //fast
    unsigned char LUT[256];
    AAtime = getTickCount();
    for (int i = 0; i < 256; ++i)
    {
        int t = i * 1.14;
        t = (t > 255) ? 255 : t;
        LUT[i] = t;
    }

    for (int i = 0; i < 1000; ++i)
        for (int j = 0; j < 1000; ++j)
            O[i][j] = LUT[O[i][j]];
    
    BBtime = getTickCount();
    printf("using lut %.5lf sec \n", (BBtime - AAtime) / getTickFrequency()); //chec

    return 0;
}
...