/
CppDoHistogramEqualization.txt
executable file
·62 lines (58 loc) · 2.47 KB
/
CppDoHistogramEqualization.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//From http://www.richelbilderbeek.nl/CppDoHistogramEqualization.htm
void DoHistogramEqualization(const TImage * const source, TImage * const target)
{
assert(source!=0 && "Source image is NULL");
assert(target!=0 && "Target image is NULL");
assert(source->Picture->Bitmap!=0 && "Source bitmap is NULL");
assert(target->Picture->Bitmap!=0 && "Target bitmap is NULL");
assert(source->Picture->Bitmap->PixelFormat == pf24bit && "Source bitmap must be 24 bit");
assert(target->Picture->Bitmap->PixelFormat == pf24bit && "Target bitmap must be 24 bit");
//Get the width and height from the source
const int width = source->Picture->Bitmap->Width;
const int height = source->Picture->Bitmap->Height;
//Set the target's width and height
target->Picture->Bitmap->Width = width;
target->Picture->Bitmap->Height = height;
const int surface = width * height;
const int nGreyValues = 256; //There are 256 different pixel intensities
const std::vector<int> histogram = GetImageHistogram(source);
assert(nGreyValues==static_cast<int>(histogram.size()));
const std::vector<int> cumulativeHistogram = GetCumulativeHistogram(histogram);
assert(nGreyValues==static_cast<int>(cumulativeHistogram.size()));
//Works, but anybody knows how to use std::for_each or std::transform for this?
std::vector<int> rescaledHistogram(nGreyValues,0);
for (int i=0; i!=nGreyValues; ++i)
{
//'surface + 1' to prevent that rescaledGreyValue == 256
const int rescaledGreyValue
= static_cast<int>(
static_cast<double>(nGreyValues)
* static_cast<double>(cumulativeHistogram[i])
/ static_cast<double>(surface + 1) );
assert(rescaledGreyValue >= 0);
assert(rescaledGreyValue < 256);
rescaledHistogram[i] = rescaledGreyValue;
}
for (int y=0; y!=height; ++y)
{
const unsigned char * lineSource
= static_cast<const unsigned char *>(
source->Picture->Bitmap->ScanLine[y]);
unsigned char * lineTarget
= static_cast<unsigned char *>(
target->Picture->Bitmap->ScanLine[y]);
for (int x=0; x!=width; ++x)
{
const int greyOriginal
= (lineSource[x*3+0] + lineSource[x*3+1] + lineSource[x*3+2]) / 3;
assert(greyOriginal >= 0);
assert(greyOriginal < 256);
const int greyNew = rescaledHistogram[greyOriginal];
assert(greyNew >= 0);
assert(greyNew < 256);
lineTarget[x*3+0]=greyNew; //Blue
lineTarget[x*3+1]=greyNew; //Green
lineTarget[x*3+2]=greyNew; //Red
}
}
}