opencv學習(二十九)之灰度圖轉化爲二值圖adaptiveThreshold

針對圖像的閾值操作,opencv除了提供threshold函數也提供了adaptiveThreshold()函數,從字面意思可以翻譯爲自適應閾值操作,函數的主要功能是將灰度圖轉化爲二值圖像。其函數原型如下:

void cv::adaptiveThreshold  ( InputArray  src,  
  OutputArray  dst,  
  double  maxValue,  
  int  adaptiveMethod,  
  int  thresholdType,  
  int  blockSize,  
  double  C  
 ) 

參數解釋:
. InputArray src: 輸入圖像,8位單通道圖像
. OutputArray dst: 目標圖像,與輸入圖像有相同的尺寸和類型
. double maxValue: 給像素賦予的滿足閾值類型的非零值
. int adaptiveMethod: 用於指定自適應閾值的算法,具體可以查看adaptiveThresholdTypes給出的具體內容,簡要內容如下:

這裏寫圖片描述

其中ADAPTIVE_THRESH_MEAN_C方法的閾值時由blockSize確定的像素(x, y)在blockSize x blockSize範圍內的鄰域像素值減參數C得到的平均值,而ADAPTIVE_THRESH_GAUSSIAN_C中閾值是blockSize x blockSize領域範圍內減去C後的加權和。默認的sigma用於指定的blockSize,可通過getGaussianKernel查看詳細信息。
. int thresholdType: 閾值類型,其取值有兩種類型分別是:
(1).THRESH_BINARY,其數學模型公式如下所示:
這裏寫圖片描述
(2).THRESH_BINARY_INV,其數學公式如下:
這裏寫圖片描述

. int blockSize: 用於計算閾值大小的像素鄰域尺寸,取值爲3\5\7……
. double C: 自適應閾值算法中減去的常數值,通常是正數,在極少情況下式0或負值。

示例程序:

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

using namespace std;
using namespace cv;

//定義全局變量
Mat srcImage, grayImage, dstImage;

const int thresholdTypeMaxValue = 1;
int thresholdTypeValue = 0;
const int CMaxValue = 50;
int CValue = 10;
const double maxValue = 255;
int blockSize = 5;

//定義回調函數
void adaptiveThresholdFun(int, void*);

int main()
{
    Mat srcImage = imread("lena.jpg");

    //判斷圖像是否讀取成功
    if(srcImage.empty())
    {
        cout << "圖像讀取失敗!" << endl;
        return -1;
    }
    else
        cout << "圖像讀取成功!" << endl << endl;

    cvtColor(srcImage, grayImage, COLOR_RGB2GRAY);
    namedWindow("灰度圖",WINDOW_AUTOSIZE);
    imshow("灰度圖", grayImage);

    //軌跡條屬性和依附窗口設置
    namedWindow("二值圖像", WINDOW_AUTOSIZE);
    char thresholdTypeName[20];
    sprintf(thresholdTypeName, "閾值類型\n 0: THRESH_BINARY\n 1: THRESH_BINARY_INV ", thresholdTypeMaxValue);
    createTrackbar(thresholdTypeName, "二值圖像", &thresholdTypeValue, thresholdTypeMaxValue, adaptiveThresholdFun);
    adaptiveThresholdFun(thresholdTypeValue, 0);

    char CName[20];
    sprintf(CName, "常  數 %d", CMaxValue);
    createTrackbar(CName, "二值圖像", &CValue, CMaxValue, adaptiveThresholdFun);
    adaptiveThresholdFun(CValue, 0);


    waitKey(0);
    return 0;
}

void adaptiveThresholdFun(int, void*)
{
    int thresholdType;
    switch(thresholdTypeValue)
    {
    case 0:
        thresholdType = THRESH_BINARY;
        break;

    case 1:
        thresholdType = THRESH_BINARY_INV;
        break;

    default:
        break;
    }
    adaptiveThreshold(grayImage, dstImage, maxValue, ADAPTIVE_THRESH_MEAN_C,
                        thresholdType, blockSize, CValue);

    imshow("二值圖像", dstImage);
}

程序運行結果:
這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章