閾值:
- 最簡單的分割方法
- 應用示例:分離對應於我們想要分析的對象的圖像的區域。該分離基於對象像素和背景像素之間的強度變化。
- 爲了區分我們感興趣的像素(其最終將被拒絕),我們對每個像素強度值相對於閾值進行比較(根據要解決的問題確定)。
- 一旦我們正確分離了重要的像素,我們可以用一個確定的值來設置它們來識別它們(即我們可以爲它們分配值(黑色),(白色)或適合您需要的任何值)。
如下圖的分割:
閾值類型:
左下方的圖表示圖像像素點Src(x,y)值分佈情況,藍色水平線表示閾值:
閾值二值化(threshold binary)
閾值反二值化(threshold binary Inverted)
截斷 (truncate)
閾值取零 (threshold to zero)
閾值反取零 (threshold to zero inverted)
對應的參數值:
// opencv0015.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include<iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int threshold_value = 0;
int threshold_type = 3;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;
Mat src, src_gray, dst;
const char* window_name = "Threshold Demo";
const char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
const char* trackbar_value = "Value";
void Threshold_Demo(int ,void*);
int main()
{
string imageName = "D:/images/666.jpg";
src = imread(imageName,IMREAD_COLOR); //讀取一個圖片
if (src.empty())
{
cout << "load image failed" << endl;
return -1;
}
cvtColor(src, src_gray, COLOR_BGR2GRAY); //裝換成灰色圖像
namedWindow(window_name,WINDOW_AUTOSIZE);
createTrackbar(trackbar_type, window_name, &threshold_type, max_type, Threshold_Demo); //選擇閾值類型
createTrackbar(trackbar_value, window_name, &threshold_value, max_value, Threshold_Demo); //選擇閾值的值
Threshold_Demo(0,0);
waitKey(0);
return 0;
}
void Threshold_Demo(int, void *)
{
/* 0: Binary
1: Binary Inverted
2: Threshold Truncated
3: Threshold to Zero
4: Threshold to Zero Inverted
*/
threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);
imshow(window_name, dst);
}
簡單介紹一下函數:
threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);
- src_gray 輸入圖像,這裏是灰度圖像,你可以使用原圖像,效果有些不同
- dst 輸出圖像
- threshold_value 當前輸入的閾值,這個根據情況來選擇 0~255;
- max_BINARY_value,設置閾值的最大值;
- threshold_type 閾值的種類,上邊有明細。
那我們看看結果吧:
截斷:
閾值二值化與反向二值化:
閾值與零與倒置
是不是非常的簡單,喜歡的話就一起來學習吧,可以關注我的博客,一起成長與進步吧。