可变阈值二值化


可变阈值二值化

代码如下(示例):

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
#define WINDOW_NAME "【二值化】"    
int g_nThresholdValue = 100;
int g_nThresholdType = 3;
Mat g_srcImage, g_grayImage, g_dstImage;
static void ShowHelpText();//输出帮助文字
void on_Threshold(int, void*);//回调函数
int main()
{
    //改变console字体颜色
    system("color 1F");

    //显示欢迎和帮助文字
    ShowHelpText();

    //读入源图片
    g_srcImage = imread("D:\\Images\\test1.png");
    if (!g_srcImage.data) { printf("读取图片错误,请确定目录下是否有imread函数指定的图片存在~! \n"); return false; }
    imshow("原始图", g_srcImage);

    //存留一份原图的灰度图
    // opencv3:CV_RGB2GRAY
    // opencv4:COLOR_RGB2GRAY
    cvtColor(g_srcImage, g_grayImage, COLOR_RGB2GRAY);

    //创建窗口并显示原始图
    // opencv3:CV_WINDOW_AUTOSIZE
    // opencv4:WINDOW_AUTOSIZE
    namedWindow(WINDOW_NAME, WINDOW_AUTOSIZE);

    //创建滑动条来控制阈值
    createTrackbar("模式", WINDOW_NAME, &g_nThresholdType, 4, on_Threshold);
    createTrackbar("参数值", WINDOW_NAME, &g_nThresholdValue, 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(g_grayImage, g_dstImage, g_nThresholdValue, 255, g_nThresholdType);

    //更新效果图
    imshow(WINDOW_NAME, g_dstImage);
}

static void ShowHelpText()
{
    printf("\n\n  ----------------------------------------------------------------------------\n");
    //输出一些帮助信息  
    printf("\n\t欢迎来到【基本阈值操作】示例程序~\n\n");
    printf("\n\t按键操作说明: \n\n"
        "\t\t键盘按键【ESC】- 退出程序\n"
        "\t\t滚动条模式0- 二进制阈值\n"
        "\t\t滚动条模式1- 反二进制阈值\n"
        "\t\t滚动条模式2- 截断阈值\n"
        "\t\t滚动条模式3- 反阈值化为0\n"
        "\t\t滚动条模式4- 阈值化为0\n");
}

二值化展示

请添加图片描述

请添加图片描述

请添加图片描述
请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值