本系列代码托管于:https://github.com/chintsan-code/opencv4-tutorials

本篇使用的项目为:adaptive_threshold

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, const char** argv) {
	Mat src = imread("../sample/master.jpg");
	if (src.empty()) {
		cout << "could not load image..." << endl;
		return -1;
	}
	namedWindow("input", WINDOW_AUTOSIZE);
	imshow("input", src);
	Mat gray, binary;
	cvtColor(src, gray, COLOR_BGR2GRAY);
	imshow("input", gray);

	double t1 = threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
	imshow("otsu binary", binary);

	adaptiveThreshold(gray, binary, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 25, 10);
	imshow("ada-binary", binary);

	waitKey(0);
	destroyAllWindows();
	return 0;
}

全局阈值的局限性

对光照度不均匀的图像容易错误地进行二值化分割

自适应阈值

自适应阈值对图像模糊求差然后二值化。步骤:

  1. 盒子模糊,得到图像D
  2. 原图 + 偏置常量C,得到图像S
  3. T = S – D + 255

adaptiveThreshold:对图像使用自适应阈值分割

void adaptiveThreshold( InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C );
  • src:输入图像,8UC1
  • dst:输出图像,与src具有相同的尺寸和类型
  • maxValue:预设满足条件的最大值
  • adaptiveMethod:自适应方法
    • ADAPTIVE_THRESH_MEAN_C
    • ADAPTIVE_THRESH_GAUSSIAN_C
  • thresholdType:分割类型
  • blockSize:盒子模糊的卷积核的size
  • C:常量