niblack_thresholding.cpp 1.57 KB
Newer Older
1
/*
Amro's avatar
Amro committed
2
 * C++ sample to demonstrate Niblack thresholding.
3 4 5 6
 */

#include <iostream>
#include "opencv2/core.hpp"
Amro's avatar
Amro committed
7
#include "opencv2/highgui.hpp"
8
#include "opencv2/imgproc.hpp"
9
#include "opencv2/ximgproc.hpp"
10 11 12 13 14

using namespace std;
using namespace cv;
using namespace cv::ximgproc;

Amro's avatar
Amro committed
15 16 17 18
Mat_<uchar> src;
int k_ = 8;
int blockSize_ = 11;
int type_ = THRESH_BINARY;
19
int method_ = BINARIZATION_NIBLACK;
20 21 22 23 24

void on_trackbar(int, void*);

int main(int argc, char** argv)
{
Amro's avatar
Amro committed
25
    // read gray-scale image
26 27 28 29 30 31
    if(argc != 2)
    {
        cout << "Usage: ./niblack_thresholding [IMAGE]\n";
        return 1;
    }
    const char* filename = argv[1];
Amro's avatar
Amro committed
32
    src = imread(filename, IMREAD_GRAYSCALE);
33
    imshow("Source", src);
Amro's avatar
Amro committed
34 35 36 37

    namedWindow("Niblack", WINDOW_AUTOSIZE);
    createTrackbar("k", "Niblack", &k_, 20, on_trackbar);
    createTrackbar("blockSize", "Niblack", &blockSize_, 30, on_trackbar);
38
    createTrackbar("method", "Niblack", &method_, 3, on_trackbar);
Amro's avatar
Amro committed
39 40
    createTrackbar("threshType", "Niblack", &type_, 4, on_trackbar);
    on_trackbar(0, 0);
41 42 43 44 45 46 47
    waitKey(0);

    return 0;
}

void on_trackbar(int, void*)
{
Amro's avatar
Amro committed
48 49 50 51
    double k = static_cast<double>(k_-10)/10;                 // [-1.0, 1.0]
    int blockSize = 2*(blockSize_ >= 1 ? blockSize_ : 1) + 1; // 3,5,7,...,61
    int type = type_;  // THRESH_BINARY, THRESH_BINARY_INV,
                       // THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV
52
    int method = method_; //BINARIZATION_NIBLACK, BINARIZATION_SAUVOLA, BINARIZATION_WOLF, BINARIZATION_NICK
Amro's avatar
Amro committed
53
    Mat dst;
54
    niBlackThreshold(src, dst, 255, type, blockSize, k, method);
Amro's avatar
Amro committed
55
    imshow("Niblack", dst);
56
}