opencv阈值法实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/love_image_xie/article/details/87643540

前一个博客写了Otsu算法的实现,这个博客接着写opencv中自带的阈值实现方法:threshold以及adaptiveThreshold的应用。

threshold( const Mat& src, Mat& dst, double thresh,double maxVal, int thresholdType );

void adaptiveThreshold( InputArray src, OutputArray dst,
                        double maxValue, int adaptiveMethod,
                        int thresholdType, int blockSize, double C );

threshold函数中thresholdType参数说明:

adaptiveThreshold函数是自适应阈值方法,先计算像素局部邻域blockSize*blockSize的均值,然后减去常数C,得到阈值,再使用thresholdType确定大于阈值是255还是小于阈值是255,参数说明:

1、adaptiveMethod方法包括:ADAPTIVE_THRESH_MEAN_C(0),ADAPTIVE_THRESH_GAUSSIAN_C(1),分别表示局部邻域块的平均值以及局部邻域块的高斯加权和。

2、thresholdType可选THRESH_BINARY(0)或者THRESH_BINARY_INV(1)两种

具体实现如下:

#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/core/core.hpp>
#include<cmath>
#include<iostream>
#include<vector>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
using namespace cv;
/*
//阈值方法实现:
1、threshold二值化实现
2、adaptiveThreshold 阈值化实现
3、双阈值法的实现
*/


int main()
{
	
	Mat src = imread("E:\\研究生\\学习材料\\学习书籍\\OpenCV图像处理编程实例-源码-20160801\\《OpenCV图像处理编程实例-源码-20160801\\images\\flower.jpg");
	if (!src.data)
		return 1;
	Mat gray;
	cvtColor(src,gray,CV_BGR2GRAY);
	imshow("gray",gray);
	Mat dst1,dst2,dst3;
	//threshold二值化实现
	int thresh = 130;
	int threshType = 0;
	int maxVal = 255;
	threshold(gray,dst1,thresh,maxVal,threshType);
	imshow("threshold", dst1);

	//adaptiveThreshold 阈值化实现
	int blockSize = 5;
	int constValue = 10;
	int adaptiveMethod = 0;
	int thresholdType = 1;
	adaptiveThreshold(gray,dst2,maxVal,adaptiveMethod,thresholdType,blockSize,constValue);
	imshow("adaptiveThreshold", dst2);

	//双阈值法的实现
	int low_threshold = 150;
	int high_threshold = 210;
	Mat dst3_t1, dst3_t2;
	threshold(gray,dst3_t1,low_threshold,maxVal,cv::THRESH_BINARY);
	threshold(gray,dst3_t2,high_threshold,maxVal,cv::THRESH_BINARY_INV);
	//矩阵与运算
	bitwise_and(dst3_t1,dst3_t2,dst3);
	imshow("dst3",dst3);

	waitKey(0);
	return 0;
}


猜你喜欢

转载自blog.csdn.net/love_image_xie/article/details/87643540