Skip to content

Commit 6c7a806

Browse files
committed
fix and update niblack sample
- read image as 1-channel grayscale - 3 trackers to control function parameters - K allowed to go to negative values (usually to detect black text on white bg)
1 parent 750eea1 commit 6c7a806

File tree

1 file changed

+21
-26
lines changed

1 file changed

+21
-26
lines changed
Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,53 @@
11
/*
2-
* Sample C++ to demonstrate Niblack thresholding.
3-
*
2+
* C++ sample to demonstrate Niblack thresholding.
43
*/
54

65
#include <iostream>
7-
#include <cstdio>
8-
9-
#include "opencv2/highgui.hpp"
106
#include "opencv2/core.hpp"
7+
#include "opencv2/highgui.hpp"
118
#include "opencv2/imgproc.hpp"
12-
139
#include "opencv2/ximgproc.hpp"
1410

1511
using namespace std;
1612
using namespace cv;
1713
using namespace cv::ximgproc;
1814

19-
Mat_<uchar> src, dst;
20-
21-
const int k_max_value = 10;
22-
int k_from_slider = 0;
23-
double k_actual = 0.0;
15+
Mat_<uchar> src;
16+
int k_ = 8;
17+
int blockSize_ = 11;
18+
int type_ = THRESH_BINARY;
2419

2520
void on_trackbar(int, void*);
2621

2722
int main(int argc, char** argv)
2823
{
29-
/*
30-
* Read filename from the command-line and load
31-
* corresponding gray-scale image.
32-
*/
24+
// read gray-scale image
3325
if(argc != 2)
3426
{
3527
cout << "Usage: ./niblack_thresholding [IMAGE]\n";
3628
return 1;
3729
}
3830
const char* filename = argv[1];
39-
src = imread(filename, 1);
40-
41-
namedWindow("k-slider", 1);
42-
string trackbar_name = "k";
43-
createTrackbar(trackbar_name, "k-slider", &k_from_slider, k_max_value, on_trackbar);
44-
on_trackbar(k_from_slider, 0);
45-
31+
src = imread(filename, IMREAD_GRAYSCALE);
4632
imshow("Source", src);
33+
34+
namedWindow("Niblack", WINDOW_AUTOSIZE);
35+
createTrackbar("k", "Niblack", &k_, 20, on_trackbar);
36+
createTrackbar("blockSize", "Niblack", &blockSize_, 30, on_trackbar);
37+
createTrackbar("threshType", "Niblack", &type_, 4, on_trackbar);
38+
on_trackbar(0, 0);
4739
waitKey(0);
4840

4941
return 0;
5042
}
5143

5244
void on_trackbar(int, void*)
5345
{
54-
k_actual = (double)k_from_slider/k_max_value;
55-
niBlackThreshold(src, dst, 255, THRESH_BINARY, 3, k_actual);
56-
57-
imshow("Destination", dst);
46+
double k = static_cast<double>(k_-10)/10; // [-1.0, 1.0]
47+
int blockSize = 2*(blockSize_ >= 1 ? blockSize_ : 1) + 1; // 3,5,7,...,61
48+
int type = type_; // THRESH_BINARY, THRESH_BINARY_INV,
49+
// THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV
50+
Mat dst;
51+
niBlackThreshold(src, dst, 255, type, blockSize, k);
52+
imshow("Niblack", dst);
5853
}

0 commit comments

Comments
 (0)