#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
using namespace std;

Mat src, dst,dst2,gray_src;
char* INPUT_WIN = "input image";
char* output_title = "binary image";
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;

void Threshold_Demo(int, void*)
{
    cvtColor(src, gray_src, CV_BGR2GRAY);
    //threshold(gray_src, dst, threshold_value, threshold_max, THRESH_BINARY);
    //反二值化
    //threshold(gray_src, dst, threshold_value, threshold_max, THRESH_BINARY_INV);

    //type_value有如下类型:
    //THRESH_BINARY
    //THRESH_BINARY_INV
    //THRESH_THRESH_TRUNC 大于该阈值的像素点被设定为该阈值,小于该阈值的保持不变。
    //THRESH_THRESH_TOZERO 像素点的灰度值大于该阈值的不进行任何改变;2 像素点的灰度值小于该阈值的,其灰度值全部变为0。
    //THRESH_THRESH_TOZERO_INV
    /*threshold(gray_src, dst, threshold_value, threshold_max, type_value);*/
    //自动取阈值
    threshold(gray_src, dst, threshold_value, threshold_max, THRESH_OTSU | type_value);
    imshow(output_title, dst);
}

int main()
{
    //原图
    src = imread(".//pic//kate.png", IMREAD_UNCHANGED);


    namedWindow(INPUT_WIN, CV_WINDOW_AUTOSIZE);
    imshow(INPUT_WIN, src);
    namedWindow(output_title, CV_WINDOW_AUTOSIZE);

    createTrackbar("Threshold Value:", output_title, &threshold_value, threshold_max, Threshold_Demo);
    createTrackbar("Type Value:", output_title, &type_value, type_max, Threshold_Demo);
    Threshold_Demo(0, 0);

    waitKey(0);
    return 0;
}
12-18 02:32