adaptiveThreshold是threshold的进阶版本。threshold只是简单的把图像像素根据阈值区分,这样的二值区分比较粗糙。可能会导致图像的信息与特征完全无法提取,或者漏掉一些关键的信息。
自适应阈值处理的好处:
-
- void cv::adaptiveThreshold
- (
- InputArray src,
- OutputArray dst,
- double maxValue,
- int adaptiveMethod,
- int thresholdType,
- int blockSize,
- double C
- )
| src | 源图像 |
| dst | 输出图像 |
| maxvalue | 分配给满足条件的像素的非零值 |
| adaptiveMethod | 自适应阈值算法: ADAPTIVE_THRESH_MEAN_C (均值) ADAPTIVE_THRESH_GAUSSIAN_C (高斯) |
| thresholdType | 阈值类型: THRESH_BINARY |
| blockSize | 用于计算像素阈值的像素邻域的大小:3、5、7等 |
| c | 从平均值或加权平均值中减去常数(通常,它是正的,但也可能是零或负的) |
- #include "widget.h"
- #include "ui_widget.h"
-
- #include <QDebug>
-
- #include <opencv2/core/core.hpp>
- #include <opencv2/highgui/highgui.hpp>
- #include <opencv2/imgproc/imgproc.hpp>
-
- #include <vector>
-
- using namespace cv;
- using namespace std;
-
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- , ui(new Ui::Widget)
- {
- ui->setupUi(this);
-
- //载入原始图像
- Mat mat0 = imread("c:/opencv/logo.jpg");
- //显示
- imshow("mat",mat0);
-
- //将图像转为灰度图
- Mat im_gray;
- cv::cvtColor(mat0,im_gray,COLOR_BGR2GRAY);
- imshow("im_gray",im_gray);
-
- //自适应阈值处理
- Mat mat_ada;
- cv::adaptiveThreshold(im_gray,mat_ada,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY,3,6);
- //显示
- imshow("mat_ada",mat_ada);
-
- }
-
- Widget::~Widget()
- {
- delete ui;
- }

通过改变 blockSize 和 c 的数值,可以得到不同的处理效果:
OpenCV之自适应阈值操作:adaptiveThreshold()函数