demhist.cpp 2.33 KB
Newer Older
wester committed
1 2
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
wester committed
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

#include <iostream>

using namespace cv;
using namespace std;

int _brightness = 100;
int _contrast = 100;

Mat image;

/* brightness/contrast callback function */
static void updateBrightnessContrast( int /*arg*/, void* )
{
    int histSize = 64;
    int brightness = _brightness - 100;
    int contrast = _contrast - 100;

    /*
     * The algorithm is by Werner D. Streidt
     * (http://visca.com/ffactory/archives/5-99/msg00021.html)
     */
    double a, b;
    if( contrast > 0 )
    {
        double delta = 127.*contrast/100;
        a = 255./(255. - delta*2);
        b = a*(brightness - delta);
    }
    else
    {
        double delta = -128.*contrast/100;
        a = (256.-delta*2)/255.;
        b = a*brightness + delta;
    }

    Mat dst, hist;
    image.convertTo(dst, CV_8U, a, b);
    imshow("image", dst);

    calcHist(&dst, 1, 0, Mat(), hist, 1, &histSize, 0);
    Mat histImage = Mat::ones(200, 320, CV_8U)*255;

wester committed
46
    normalize(hist, hist, 0, histImage.rows, CV_MINMAX, CV_32F);
wester committed
47 48 49 50 51 52 53 54 55 56 57 58 59

    histImage = Scalar::all(255);
    int binW = cvRound((double)histImage.cols/histSize);

    for( int i = 0; i < histSize; i++ )
        rectangle( histImage, Point(i*binW, histImage.rows),
                   Point((i+1)*binW, histImage.rows - cvRound(hist.at<float>(i))),
                   Scalar::all(0), -1, 8, 0 );
    imshow("histogram", histImage);
}
static void help()
{
    std::cout << "\nThis program demonstrates the use of calcHist() -- histogram creation.\n"
wester committed
60
              << "Usage: \n" << "demhist [image_name -- Defaults to baboon.jpg]" << std::endl;
wester committed
61 62 63 64
}

const char* keys =
{
wester committed
65
    "{1| |baboon.jpg|input image file}"
wester committed
66 67 68 69
};

int main( int argc, const char** argv )
{
wester committed
70 71
    help();

wester committed
72
    CommandLineParser parser(argc, argv, keys);
wester committed
73
    string inputImage = parser.get<string>("1");
wester committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

    // Load the source image. HighGUI use.
    image = imread( inputImage, 0 );
    if(image.empty())
    {
        std::cerr << "Cannot read image file: " << inputImage << std::endl;
        return -1;
    }

    namedWindow("image", 0);
    namedWindow("histogram", 0);

    createTrackbar("brightness", "image", &_brightness, 200, updateBrightnessContrast);
    createTrackbar("contrast", "image", &_contrast, 200, updateBrightnessContrast);

    updateBrightnessContrast(0, 0);
    waitKey();

    return 0;
}