【OpenCV图像处理】1.14 基本阈值操作

P14、基本阈值操作

  • 图像阈值 threshold

    • 阈值 是什么?简单点说是把图像分割的标尺,这个标尺是根据什么产生的,阈值产生算法?阈值类型。(Binary segmentation)
  • 阈值类型

    • 下列图中红色部分表示图像像素点src(x,y)值分布情况,蓝色水平线表示阈值
      在这里插入图片描述

    • 阈值二值化(threshold binary)

      • 在这里插入图片描述

      • 即大于阈值的取maxVal,小于阈值的取0

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

      • 在这里插入图片描述
    • 截断 (truncate)

      • 在这里插入图片描述
    • **阈值取零 **(threshold to zero)

      • 在这里插入图片描述
    • 阈值反取零 (threshold to zero inverted)

      • 公式 & 图形:在这里插入图片描述
  • 各自枚举值对应的含义在这里插入图片描述

  • 不知道阈值是多少,应该怎样计算?

    • 使用THRESH_OTSU或者THRESH_TRIANGLE枚举值,自动算阈值,自动帮我们计算,自己输入的没用。

完整代码:

#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>

using namespace std;
using namespace cv;

#ifndef P15
#define P15 15
#endif

#if P15
Mat src;
Mat gray_src,dest;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
const char* output_title = "binary image";

//这里回调函数只能是两个参数,多个参数不能使用
void Threshold_demo( int, void *)
{
    cvtColor(src, gray_src, CV_RGB2GRAY);
    // 单通道
    threshold(gray_src, dest, threshold_value, threshold_max, THRESH_BINARY | type_value);
    //threshold(gray_src, dest, 0, 255, THRESH_TRIANGLE | type_value);
    imshow(output_title, dest);
    return ;
}
#endif

int main() {
    std::string path = "../fei.JPG";
    cv::Mat img = cv::imread(path, 5);

    if(img.empty())
    {
        std::cout << "open file failed" << std::endl;
        return -1;
    }
#if P15 //P15 阈值处理
    src = img; 
    namedWindow("input image", WINDOW_AUTOSIZE);
    namedWindow(output_title, WINDOW_AUTOSIZE);
    imshow("input image", src);
    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);

#endif
    cv::waitKey(0);
    cv::destroyAllWindows();
    return 0;
}

运行结果:
在这里插入图片描述
针对上述代码的几点说明:

  1. 使用下面的语句是因为自己这几次的代码都放在一个文件中,如果采用注释的方式,需要先加很多注释,后续才能知道对应的代码,将会非常麻烦。经过几次迭代,终于进化出以下语句,后面只用修改下面的第1、2条语句中的P值就可以实现代码的执行。完美!
    #ifndef P15
    #define P15 15
    #endif
    
    #if P15
    .....
    #endif
    
  2. 在执行上面的代码过程中,遇到了不能显示bar的问题,原因有如下几个方面:
    1. createTrackbar函数的第2个参数指示了将展示bar的窗口,所以需要回调函数Threshold_demo中的imshow窗口名应与其保持一致
    2. 解决了上面这个问题,还是不能显示bar,后来经过调试,才知道是窗口大小的问题导致的,添加namedWindow(output_title, WINDOW_AUTOSIZE);后问题解决。
  3. 另一个问题,threshold函数是针对单通道图像进行操作,所以需要进行转换,不转换将会遇到 【OpenCV错误】error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'threshold’错误。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值