其他分享
首页 > 其他分享> > 图像的二值化

图像的二值化

作者:互联网

图像二值化

简介

threshold()

简介

该函数是众多二值化方法的集成,所有的方法都实现了一个功能,就是给定一个阈值,计算所有像素灰度值与这个阈值的关系,得到最终的比较结果

double cv::threshold(src, dst, thresh, maxval, type)

THRESH_OTSUTHRESH_TRIANGLE是获取阈值的方法,并不是阈值比较方法的标志,这两个标志可以与前面5种标志一起使用,例如 THRESH_BINARY | THRESH_OTSU。这两个标志分别利用大津法(OTUS)和三角形法(TRIANGLE)结合图像灰度值分布特性获取二值化的阈值,并将阈值以函数返回值的形式给出。因此,如果该函数最后一个参数设置了这两个标志中的任何一个,那么该函数第三个参数thresh将由系统自动给出,但是在调用函数时仍然不能默认,只是程序不会使用这个数值。另外,这两个标志目前只支持输入CV_8UC1类型的图像

实现

示例代码:

#include <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    Mat_<Vec3b> img = imread("/home/kslas/OpenCV/lena.tif");
    imshow("Original", img);

    Mat_<uchar> gray;
    cvtColor(img, gray, COLOR_BGR2GRAY);

    // 彩色图像二值化
    Mat_<Vec3b> img_B, img_B_V;
    threshold(img, img_B, 125, 255, THRESH_BINARY);
    threshold(img, img_B_V, 125, 255, THRESH_BINARY_INV);
    imshow("img_B", img_B);
    imshow("imgB_V", img_B_V);

    // 灰度图BINARY二值化
    Mat_<uchar> gray_B, gray_B_V;
    threshold(gray, gray_B, 125, 255, THRESH_BINARY);
    threshold(gray, gray_B_V, 125, 255, THRESH_BINARY_INV);
    imshow("gray_B", gray_B);
    imshow("gray_B_V", gray_B_V);

    // 灰度值TOZERO变换
    Mat_<uchar> gray_T, gray_T_V;
    threshold(gray, gray_T, 125, 255, THRESH_TOZERO);
    threshold(gray, gray_T_V, 125, 255, THRESH_TOZERO_INV);
    imshow("gray_T", gray_T);
    imshow("gray_T_V", gray_T_V);

    // 灰度值TRUNC变换
    Mat_<uchar> gray_TRUNC;
    threshold(gray, gray_TRUNC, 125, 255, THRESH_TRUNC);
    imshow("gray_TRUNC", gray_TRUNC);

    // 灰度图像大津法和三角形法二值化
    Mat_<uchar> img_Thr = imread("/home/kslas/OpenCV/dark.png", 0);
    Mat_<uchar> img_Thr_O, img_Thr_T;
    threshold(img_Thr, img_Thr_O, 100, 255, THRESH_BINARY | THRESH_OTSU);
    threshold(img_Thr, img_Thr_T, 125, 255, THRESH_BINARY | THRESH_TRIANGLE);
    imshow("img_Thr", img_Thr);
    imshow("img_Thr_O", img_Thr_O);
    imshow("img_Thr_T", img_Thr_T);

    waitKey(0);
    destroyAllWindows();
    return 0;
}

运行结果:

adaptiveThreshold()

简介

void cv::adaptiveThreshold(src, dst, maxValue, adaptiveMethod, thresholdType, blockSize, C)

实现

示例代码:

#include <opencv2/opencv.hpp>
using namespace cv;

int main()
{
    Mat_<uchar> img_Thr = imread("/home/kslas/OpenCV/dark.png", 0);

    // 灰度图像自适应二值化
    Mat_<uchar> adaptive_mean, adaptive_gauss;
    adaptiveThreshold(img_Thr, adaptive_mean, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 55, 0);
    adaptiveThreshold(img_Thr, adaptive_gauss, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 55, 0);
    imshow("img_Thr", img_Thr);
    imshow("adaptive_mean", adaptive_mean);
    imshow("adaptive_gauss", adaptive_gauss);

    waitKey(0);
    destroyAllWindows();
    return 0;
}

运行结果:

标签:gray,img,阈值,Thr,THRESH,图像,灰度,二值化
来源: https://www.cnblogs.com/TNTksals/p/15834076.html