基本阈值操作

opencv中有两个进行阈值操作的API,分别是固定阈值操作函数Threshold()和自适应阈值函数adaptiveThreshold()

其中固定阈值操作函数里面有5中类型的对图像进行取阈值的方法。程序中使用了滑动条来切换阈值类型和阈值参数,示例如下:

#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<iostream>

using namespace cv;
using namespace std;


//定义全局变量
Mat src, gray, dst;//定义Mat类型的src,gray,和dst

int threshold_value = 100;
int threshold_type = 3;

//定义阈值大小和类型的阈值函数
void on_threshold(int, void*);

int main()
{
    src = imread("D:/meinv.jpg");  //读取原图
    namedWindow("效果图", CV_WINDOW_AUTOSIZE);
    
    cvtColor(src, gray, CV_BGR2GRAY);//转化为灰度图

    createTrackbar("模式", "效果图", &threshold_type, 4, on_threshold);
    createTrackbar("参数值", "效果图", &threshold_value, 255, on_threshold);

    //初始化自定义的阈值回调函数
    on_threshold(0, 0);

    //轮询等待用户 按键,如果按下ESC键则退出程序
    while (1)
    {
        int key;
        key = waitKey(20);
        if ((char)key == 27)
            break;
    }

}

void on_threshold(int,void *)
{
    //调用阈值函数
    threshold(gray, dst, threshold_value, 255, threshold_type);
    imshow("效果图",dst);

}

显示效果:

原文地址:https://www.cnblogs.com/carlber/p/9661799.html