opencv自适应阈值原理
1、先将原图像进行平滑(均值平滑,中值平滑,高斯平滑…),得到一个平滑后的图像记为smoothImg;
2、得到自适应矩阵 Thresh = (1-ratio)*smoothImg ; ratio一般为0.15
3、利用局部阈值进行分割 , 即利用Thresh和原图进行比较分割
优点是对于光照不均匀的图像进行二值化处理,相对会比全局性的二值化(OTSU算法和最大熵算法、全局Thresh)效果会好。
adaptiveThreshold参数意义
@param src Source 8-bit single-channel image.
@param dst Destination image of the same size and the same type as src.
@param maxValue Non-zero value assigned to the pixels for which the condition is satisfied
@param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes.
The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries.
@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV,
see #ThresholdTypes.
@param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the
pixel: 3, 5, 7, and so on.
@param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it
is positive but may be zero or negative as well.
@sa threshold, blur, GaussianBlur
*/
CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst,
double maxValue, int adaptiveMethod,
int thresholdType, int blockSize, double C );
参数 | 意义 |
---|---|
src | 源图像 |
dst | 输出图像 |
maxValue | 超过阈值的部分值设置为 maxvalue |
adaptiveMethod | 在一个邻域内计算阈值所采用的算法, 有两个取值,分别为 ADAPTIVE_THRESH_MEAN_C 和 ADAPTIVE_THRESH_GAUSSIAN_C (1)、ADAPTIVE_THRESH_MEAN_C的计算方法是计算出领域的平均值再减去第七个参数2的值。 (2)、ADAPTIVE_THRESH_GAUSSIAN_C的计算方法是计算出领域的高斯均值再减去第七个参数2的值 |
thresholdType | 1、THRESH_BINARY 原图灰度值大于矩阵取最大值 2、THRESH_BINARY_INV,与 1 相反 |
blockSize | 矩阵大小 |
c | 确定完阈值之后的一个微调,在原有的基础上加上 C |
void MainWindow::on_pushButton_clicked()
{
Mat srcImg = imread("D:\\5.jpg",0);
if(srcImg.empty())
{
QMessageBox::information(this,"警告","图片读取失败,请检查图片路径!");
return;
}
QImage qImg = QImage((unsigned char*)(srcImg.data), srcImg.cols,
srcImg.rows, srcImg.cols*srcImg.channels(), QImage::Format_Grayscale8);
ui->label->resize(640,480);
ui->label->setPixmap(QPixmap::fromImage(qImg.scaled(ui->label->size(), Qt::KeepAspectRatio)));
}
//自适应阈值
int MainWindow::myjAutoThresh(Mat& p_srcImg , Mat &p_dstImg)
{
adaptiveThreshold(p_srcImg , p_dstImg , 255 , 1 , 1 , 15 , 0);
return 0;
}