OpenCV学习 day8 图像基本阈值操作

 

五种阈值处理方法:

阈值二值化

大于某阈值的像素值变为指定最大值,小于某阈值的像素值变为零

 

 

小于某阈值的像素值变为指定最大值,大于某阈值的像素值变为零

 

 阈值截断

 

 阈值取零

小于某阈值的像素值变为零

 

大于某阈值的像素值变为零

 

 

两种阈值寻找方法:

两种算法:

THRESH_OTSU   该方法基于最大类间,在类间方差最大的情况下是最佳的,就图像的灰度值而言,OTSU给出最好的类间分离的阈值。如果图像黑白分明,就可以用这个

THRESH_TRAINGLE  三角法取阈值 根据直方图计算

 

综上:

使用这些阈值方法必须图像是八位

 

 

完整代码演示:

#include <iostream>
#include <opencv2/opencv.hpp>
#include <math.h>


using namespace cv;
using namespace std;

Mat src, gray_src, dst;
int threshold_value = 127;
int threshold_max = 255;
int threshold_type = 2;
int threshold_type_max = 4;
const char* output_title = "binary image";
void Threshold_Demo(int, void*);


int main(int argc, char** argv) {
    src = imread("D:/Learning/image/1.jpg");
    if (src.empty()) {
        printf("not image\n");
        return -1;
    }
    namedWindow("input image", WINDOW_AUTOSIZE);
    namedWindow(output_title, WINDOW_AUTOSIZE);  //要显示trackbar 必须有这步
    imshow("input image", src);
    createTrackbar("Treshold Value", output_title, &threshold_value, threshold_max, Threshold_Demo);
    //5种取阈值的方法随意滑动
    createTrackbar("Treshold Type", output_title, &threshold_type, threshold_type_max, Threshold_Demo);
    Threshold_Demo(0, 0);

    waitKey(0);
    return 0;
}

void Threshold_Demo(int, void*) {
    cvtColor(src, gray_src, COLOR_BGR2GRAY);
    threshold(gray_src, dst, threshold_value, threshold_max, threshold_type); 
    //threshold(gray_src, dst, 0, 255, THRESHOLD_OTSU | threshold_type);  //THRESHOLD_OTSU和THRESHOLD_TRAINGLE自动取阈值
    imshow(output_title, dst);
}

 

posted @ 2020-04-30 17:51  xyfun72  阅读(186)  评论(0编辑  收藏  举报