histogramEqualize.cpp

Go to the documentation of this file.
00001 
00015 #include <limits>
00016 #include <numeric>
00017 #include <sstream>
00018 #include <dlrComputerVision/histogramEqualize.h>
00019 
00020 namespace dlr {
00021 
00022   namespace computerVision {
00023     
00024     // This function computes the histogram of an image.
00025     Array1D<unsigned int>
00026     getHistogram(const Image<GRAY8>& inputImage)
00027     {
00028       if(inputImage.size() > std::numeric_limits<unsigned int>::max()) {
00029         std::ostringstream message;
00030         message << "Currently, we can only equalize images with "
00031                 << std::numeric_limits<int>::max() << " or fewer pixels.";
00032         DLR_THROW(ValueException, "histogramEqualize()", message.str().c_str());
00033       }
00034 
00035       Array1D<unsigned int> histogram(
00036         std::numeric_limits<Image<GRAY8>::PixelType>::max());
00037       histogram = 0;
00038       for(size_t pixelIndex = 0; pixelIndex < inputImage.size(); ++pixelIndex) {
00039         ++(histogram[inputImage[pixelIndex]]);
00040       }
00041       return histogram;
00042     }
00043   
00044   
00045     // This function remaps the pixel values of the input image in such
00046     // a way that output pixel value increases monotonically with input
00047     // pixel value, and the histogram of the output image is nearly
00048     // flat.
00049     Image<GRAY8>
00050     histogramEqualize(const Image<GRAY8>& inputImage)
00051     {
00052       // Compute the histogram and CDF.
00053       Array1D<unsigned int> histogram = getHistogram(inputImage);
00054       Array1D<unsigned int> cdf(histogram.size());
00055       std::partial_sum(histogram.begin(), histogram.end(), cdf.begin(),
00056                        std::plus<unsigned int>());
00057 
00058       // Rescale the image according to the CDF.
00059       Image<GRAY8> outputImage(inputImage.rows(), inputImage.columns());
00060       double scaleFactor = 256.0 / (inputImage.size() + 1);
00061       for(size_t pixelIndex = 0; pixelIndex < inputImage.size(); ++pixelIndex) {
00062         outputImage[pixelIndex] =
00063           static_cast<Int8>(scaleFactor * cdf[inputImage[pixelIndex]]);
00064       }
00065       return outputImage;
00066     }
00067 
00068   } // namespace computerVision    
00069 
00070 } // namespace dlr

Generated on Wed Nov 25 12:15:05 2009 for dlrComputerVision Utility Library by  doxygen 1.5.8