2020.11.04 使用OpenCV进行图像阈值分割操作【OpenCV C++】

使用函数threshold()进行图像分割

源代码:

// testOpencv13.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

Mat src,graySrc,dst;
const char* inWin = "input window";
const char* outWin = "output window";
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
void ThresholdDemo(int,void*);

int main()
{
    //std::cout << "Hello World!\n";

    src = imread("E:/imageSources/3.jpg");
    if (!src.data)
    {
        printf("cannot load image!");
        return -1;
    }

    namedWindow(inWin,WINDOW_AUTOSIZE);
    imshow(inWin,src);
    namedWindow(outWin,WINDOW_AUTOSIZE);
    //添加调整thresholdValue值得滑动条
    createTrackbar("ThresholdValue",outWin,&threshold_value, threshold_max,ThresholdDemo);
    ThresholdDemo(0,0);
    //添加调节不同阈值处理类型的滑动条
    createTrackbar("ThresholdType",outWin,&type_value,type_max, ThresholdDemo);
    waitKey(0);
    return 0;
}

void ThresholdDemo(int, void*) {
    //转换为灰度值
    cvtColor(src,graySrc,COLOR_RGB2GRAY);
    //二值化阈值
    //threshold(graySrc,dst, threshold_value, threshold_max,THRESH_BINARY);
    //调节4种不同阈值处理方法,再调节阈值处理
    threshold(graySrc, dst, threshold_value, threshold_max, type_value);
    //自动计算阈值
    //threshold(graySrc, dst, 0,255, THRESH_OTSU| type_value);
    //三角根据直方图计算阈值
    //threshold(graySrc, dst, 0, 255,THRESH_TRIANGLE| type_value);

    imshow(outWin,dst);
}

调节阈值处理类型bar和阈值bar的处理效果:

第一种:

2020.11.04 使用OpenCV进行图像阈值分割操作【OpenCV C++】

第二种:

2020.11.04 使用OpenCV进行图像阈值分割操作【OpenCV C++】

第三种:

2020.11.04 使用OpenCV进行图像阈值分割操作【OpenCV C++】

第四种:

2020.11.04 使用OpenCV进行图像阈值分割操作【OpenCV C++】

第五种:

2020.11.04 使用OpenCV进行图像阈值分割操作【OpenCV C++】