Skip to content

Instantly share code, notes, and snippets.

@sumit4iit
Created October 11, 2013 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sumit4iit/6931612 to your computer and use it in GitHub Desktop.
Save sumit4iit/6931612 to your computer and use it in GitHub Desktop.
Intensity Levels
#include<iostream>
#include "cv.h"
#include "highgui.h"
#include <cstring>
using namespace cv;
using namespace std;
// Look up table for intensity values.
int LuT[256];
// Initialize look up table according to number of intensity levels.
// For example if steps == 2 then every value in table is either 255/2 or 255.
// similarly for steps == 4 values are 255/4 , 2* 255/4, 3* 255/4 and 255.
void lookUpTable(int steps)
{
steps = 255/steps;
for(int i= 0 ; i< 256; i++)
{
LuT[i] = (i/steps)*steps;
}
}
void intensityLevels(Mat image, int step)
{
// initialize LuT
lookUpTable(step);
int channels = image.channels();
if(channels == 1)
{
for(typeof(image.begin<uchar>()) it = image.begin<uchar>(); it!=image.end<uchar>(); it++ )
{
// Map current intensity to new level.
*it = LuT[*it];
}
}
else if(channels == 3)
{
for(typeof(image.begin<Vec3b>())it = image.begin<Vec3b>(); it!= image.end<Vec3b>(); it++ )
{
// For every channel map intensity to new level.
(*it)[0] = LuT[(*it)[0]];
(*it)[1] = LuT[(*it)[1]];
(*it)[2] = LuT[(*it)[2]];
}
}
}
int main()
{
// path of image.
string path = "res/download.jpg";
// read color image
Mat image = imread(path,CV_LOAD_IMAGE_GRAYSCALE);
if(!image.data)
{
cout<<"fail\n";
return -1;
}
// create clone of the image.
Mat In = image.clone();
int no_of_levels = 2;
cout<<"Please enter no. of intensity levels"<<endl;
cin>>no_of_levels;
if(no_of_levels < 2 )
no_of_levels = 2;
//
intensityLevels(image,no_of_levels);
namedWindow("original",CV_WINDOW_AUTOSIZE);
namedWindow("out",CV_WINDOW_AUTOSIZE);
imshow("out",image);
imshow("original",In);
waitKey(0);
imwrite("res/original.png",In);
imwrite("res/out.png",image);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment