局部阈值二值化opencv c++代码实现
时间: 2023-08-30 07:09:19 浏览: 58
以下是局部阈值二值化的 OpenCV C++ 代码实现:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("test.jpg", 0); // 读取灰度图像
if (img.empty()) // 图像读取失败
{
cout << "Could not read the image" << endl;
return -1;
}
Mat bw; // 二值化图像
adaptiveThreshold(img, bw, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 10); // 进行局部阈值二值化
// 第4个参数:计算阈值的方式,这里使用均值
// 第5个参数:二值化方式,这里选用 THRESH_BINARY
// 第6个参数:计算阈值时使用的像素邻域大小
// 第7个参数:阈值减去常量值
imshow("Original Image", img);
imshow("Adaptive Thresholding", bw);
waitKey(0);
return 0;
}
```
在上述代码中,我们首先使用 `imread()` 函数读取灰度图像。接着,我们使用 `adaptiveThreshold()` 函数进行局部阈值二值化。最后,我们使用 `imshow()` 函数显示原始图像和二值化后的图像,并使用 `waitKey()` 函数等待用户按下任意键后退出程序。