niblack_thresholding.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * C++ sample to demonstrate Niblack thresholding.
  3. */
  4. #include <iostream>
  5. #include "opencv2/core.hpp"
  6. #include "opencv2/highgui.hpp"
  7. #include "opencv2/imgproc.hpp"
  8. #include "opencv2/ximgproc.hpp"
  9. using namespace std;
  10. using namespace cv;
  11. using namespace cv::ximgproc;
  12. Mat_<uchar> src;
  13. int k_ = 8;
  14. int blockSize_ = 11;
  15. int type_ = THRESH_BINARY;
  16. int method_ = BINARIZATION_NIBLACK;
  17. void on_trackbar(int, void*);
  18. int main(int argc, char** argv)
  19. {
  20. // read gray-scale image
  21. if(argc != 2)
  22. {
  23. cout << "Usage: ./niblack_thresholding [IMAGE]\n";
  24. return 1;
  25. }
  26. const char* filename = argv[1];
  27. src = imread(filename, IMREAD_GRAYSCALE);
  28. imshow("Source", src);
  29. namedWindow("Niblack", WINDOW_AUTOSIZE);
  30. createTrackbar("k", "Niblack", &k_, 20, on_trackbar);
  31. createTrackbar("blockSize", "Niblack", &blockSize_, 30, on_trackbar);
  32. createTrackbar("method", "Niblack", &method_, 3, on_trackbar);
  33. createTrackbar("threshType", "Niblack", &type_, 4, on_trackbar);
  34. on_trackbar(0, 0);
  35. waitKey(0);
  36. return 0;
  37. }
  38. void on_trackbar(int, void*)
  39. {
  40. double k = static_cast<double>(k_-10)/10; // [-1.0, 1.0]
  41. int blockSize = 2*(blockSize_ >= 1 ? blockSize_ : 1) + 1; // 3,5,7,...,61
  42. int type = type_; // THRESH_BINARY, THRESH_BINARY_INV,
  43. // THRESH_TRUNC, THRESH_TOZERO, THRESH_TOZERO_INV
  44. int method = method_; //BINARIZATION_NIBLACK, BINARIZATION_SAUVOLA, BINARIZATION_WOLF, BINARIZATION_NICK
  45. Mat dst;
  46. niBlackThreshold(src, dst, 255, type, blockSize, k, method);
  47. imshow("Niblack", dst);
  48. }