阈值操作

阈值二值化:
设定一个临界值,将像素值大于临界值的像素设置成255,低于临界值设置成0。

dst(x,y)={maxVal0ifsrc(x,y)>threshotherwise

阈值反二值化:
设定一个临界值,将像素值大于临界值的像素设置成0,低于临界值设置成255。
dst(x,y)={0maxValifsrc(x,y)>threshotherwise

截断:
设定一个临界值,将像素值大于临界值的像素设置成临界值,低于临界值不变。
dst(x,y)={threshholdsrc(x,y)ifsrc(x,y)>threshotherwise

阈值取0:
设定一个临界值,将像素值大于临界值的像素不变,低于临界值设置成0。
dst(x,y)={src(x,y)0ifsrc(x,y)>threshotherwise

阈值反取0:
设定一个临界值,将像素值大于临界值的像素设置成0,低于临界值不变。
dst(x,y)={0src(x,y)ifsrc(x,y)>threshotherwise

CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
                               double thresh, double maxval, int type );

参数src:输入8位灰度图像,彩色图像会报错,无法运行
参数dst:输出二值图像
参数thresh:临界值
参数maxval:最大灰度值,255
参数type:阈值类型
阈值操作_第1张图片
在不知道具体阈值应该选择多少的情况下,type可以用THRESH_OTSU和THRESH_TRIANGLE,通过内部计算自动选择用、适应阈值。

原图像:
阈值操作_第2张图片

    threshold(gray_src, dst, threshold_value, threshold_max, type_value);

二值化:
阈值操作_第3张图片
反二值化:
阈值操作_第4张图片
截断:
阈值操作_第5张图片
取0:
阈值操作_第6张图片
反取0:
阈值操作_第7张图片
如果不知道具体应该选择阈值是多少的情况下,可以选择

    threshold(gray_src, dst, 0, 255, THRESH_OTSU|type_value);

如果参数type仅为THRESH_OTSU,输出只有正常二值图。
阈值操作_第8张图片
若参数type为THRESH_OTSU|type_value,则可以选择不同方式下的自动阈值。
阈值操作_第9张图片

#include 
#include
#include

using namespace std;
using namespace cv;

Mat src, dst, gray_src;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
char input_win[] = "inout image";
const char* output_win = "outputimage";

void ThreholdDemo(int, void*);

int main(int argc, char** argv)
{
    src = imread("cat.jpg");
    if (src.empty())
    {
        cout << "could not load image..." << endl;
        return -1;
    }

    namedWindow(input_win, CV_WINDOW_AUTOSIZE);
    namedWindow(output_win, CV_WINDOW_AUTOSIZE);
    imshow(input_win, src);

    createTrackbar("Threshold Value", output_win, &threshold_value, threshold_max, ThreholdDemo);
    createTrackbar("type Value", output_win, &type_value, type_max, ThreholdDemo);

    ThreholdDemo(0, 0);


    waitKey(0);
    return 0;
}

void ThreholdDemo(int, void*)
{
    cvtColor(src, gray_src, CV_BGR2GRAY);

    threshold(gray_src, dst, threshold_value, threshold_max, type_value);
    //threshold(gray_src, dst, 0, 255, THRESH_OTSU | type_value);
    imshow(output_win, dst);
}

你可能感兴趣的:(OpenCV笔记)