【VC++、OpenCV3.4】阈值操作

阈值操作:threshold

阈值:图像分割的标尺。最简单的就是二值化,大于阈值的像素值全部变成255,小于阈值的像素值全部设置为0.

阈值操作其实有很多种类型:

阈值二值化,反二值化(threshold binary Inverted)

阈值截断(truncate):大于阈值的部分像素值取0,阈值范围内的部分等于原来的像素值。

阈值取零(threshold to zero):大于阈值的部分与原来的像素值相等,小于阈值的部分取0

阈值反取零(threshold tozero inverted):大于阈值的部分取0,小于阈值的部分与原来像素值相等。

1、两种阈值的寻找方法

THRESH_OTSU(根据给的数自动计算阈值),THRESH_TRIANGLE(根据直方图计算阈值)

2、五种阈值的处理方法

THRESHOLD_BINARY,      THRESHOLD_BINARY_INV,     THRESHOLD_TRUNC,    THRESHOLD_TOZERO,   THRESHOLD_TOZERO_INV

【VC++、OpenCV3.4】阈值操作

/*
@param src input array (multiple-channel, 8-bit or 32-bit floating point).
@param dst output array of the same size  and type and the same number of channels as src.
@param thresh threshold value.
@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding
types.
@param type thresholding type (see #ThresholdTypes).
@return the computed threshold value if Otsu's or Triangle methods used.

@sa  adaptiveThreshold, findContours, compare, min, max
 */
CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
                               double thresh, double maxval, int type );

【VC++、OpenCV3.4】阈值操作

int type的对相应数字:

enum ThresholdTypes {
    THRESH_BINARY     = 0,
    THRESH_BINARY_INV = 1,
    THRESH_TRUNC      = 2,
    THRESH_TOZERO     = 3,
    THRESH_TOZERO_INV = 4,
    THRESH_MASK       = 7,
    THRESH_OTSU       = 8,
    THRESH_TRIANGLE   = 16
};

【VC++、OpenCV3.4】阈值操作

 

关于OTSU(最大类间方差)算法:最大类间方差

以及参考OpenCV的文档:https://docs.opencv.org/3.4.1/d7/d4d/tutorial_py_thresholding.html

                                                【VC++、OpenCV3.4】阈值操作

以及自适应阈值处理:

                                                【VC++、OpenCV3.4】阈值操作

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

using namespace cv;

const String path = "C:\\Users\\admin\\Desktop\\demo.jpg";
const String Output_Window = "Output_window";
Mat src = imread(path, IMREAD_REDUCED_COLOR_2);
Mat dst, dst2,dst3,dst4;


void Threshold_Demo(int, void *);
int threshlod_value = 100;
int threshold_max = 255;
int type = 0;
int type2 = 4;
int main(int argc, char**argv) {

	if (!src.data)
	{
		printf("Could not load the demo image...");
		return false;
	}

	namedWindow("Source Pic", CV_WINDOW_AUTOSIZE);
	imshow("Source Pic", src);

	namedWindow(Output_Window, CV_WINDOW_AUTOSIZE);//在使用createTrackbar之前需要先创建窗口
	createTrackbar("Threshold_bar", Output_Window, &threshlod_value, threshold_max, Threshold_Demo);
	createTrackbar("Type_bar", Output_Window, &type, type2, Threshold_Demo);
	Threshold_Demo(0, 0);
	

	waitKey(0);
	return 0;
}
void Threshold_Demo(int, void *) {

	cvtColor(src, dst, CV_BGR2GRAY);
	threshold(dst, dst2, threshlod_value, threshold_max, type);

	imshow(Output_Window , dst2);
}

【VC++、OpenCV3.4】阈值操作