生活随笔
收集整理的這篇文章主要介紹了
OpenCV基本的阈值操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目的:
使用OpenCV 中的函數cv::threshold實現閾值操作
理論:
閾值? 1) 最簡單的分割方法 2) 應用實例:從圖像中分割出我們要分析的對象區域。這種分離基于對象的像素和背景像素之間的強度的變化實現。 3) 為了區分我們感興趣的像素(which will eventually be rejected),我們將用每一個像素的值和threshold比較(依據要解決的問題確定)。 4) 一旦我們正確的分離出重要的像素,我們可以將這些像素的值設置成一個確定的值來確定它們(例如,可以用0表示黑色,255表示白色或任何你需要的值)。
閾值的類型
1) 基于OpenCV中的函數cv::threshold可以進行5中閾值類型。
2) 為了說明閾值操作如何工作, 考慮我們有一個原圖,圖像像素的灰度值為 s r c ( x , y ) . 如下圖描繪藍色的水平線表示閾值 t h r e s h (固定值).
閾值二值化
這個閾值操作可以表示為 :
如果 src ( x , y ) 的像素值大于 thresh ,像素值將被設置成 MaxVal .反之設置成 0 .
反向閾值二值化
這個閾值操作可以表示為 :
如果 src ( x , y ) 的像素值大于 thresh ,像素值將被設置成 0 .反之設置成 MaxVal .
截斷
這個閾值操作可以表示為 :
圖像最大的像素值為 thresh ,如果 src ( x , y ) 的像素值大于閾值 ,像素值將會被截斷為閾值 .如下圖所示 :
低于閾值零化
這個閾值操作可以表示為 :
如果 src ( x , y ) 的像素值低于 thresh ,像素的值將會被設置成 0 .
反向低于閾值零化 這個閾值操作可以表示為 :
如果 src ( x , y ) 的像素值大于 thresh ,像素的值會設置成 0 .
/**
* @file Threshold.cpp
* @brief Sample code that shows how to use the diverse threshold options offered by OpenCV
* @author OpenCV team
*/#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"using namespace cv;/// Global variablesint 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";/// Function headers
void Threshold_Demo( int, void* );/**
* @function main
*/
int main( int, char** argv )
{//! [load]src = imread( argv[1], IMREAD_COLOR ); // Load an imageif( src.empty() ) return -1;cvtColor( src, src_gray, COLOR_BGR2GRAY ); // Convert the image to Gray//! [load]//! [window]namedWindow( window_name, WINDOW_AUTOSIZE ); // Create a window to display results//! [window]//! [trackbar]createTrackbar( trackbar_type,window_name, &threshold_type,max_type, Threshold_Demo ); // Create Trackbar to choose type of ThresholdcreateTrackbar( trackbar_value,window_name, &threshold_value,max_value, Threshold_Demo ); // Create Trackbar to choose Threshold value//! [trackbar]Threshold_Demo( 0, 0 ); // Call the function to initialize/// Wait until user finishes programfor(;;){int c;c = waitKey( 20 );if( (char)c == 27 ) break;}}//![Threshold_Demo]
/**
* @function Threshold_Demo
*/
void Threshold_Demo( int, void* )
{/* 0: Binary1: Binary Inverted2: Threshold Truncated3: Threshold to Zero4: Threshold to Zero Inverted*/threshold( src_gray, dst, threshold_value, max_BINARY_value,threshold_type );imshow( window_name, dst );
}
//![Threshold_Demo]
結果
1)原圖
2)對原圖像使用反向閾值二值化 。圖像中doggie的舌頭和眼睛比較亮,像素值大于閾值所以顯示成黑色。s h
3)使用 低于閾值零化 操作。低于閾值的像素將會變成全黑,大于閾值的像素不變。如下圖所示:
總結
以上是生活随笔 為你收集整理的OpenCV基本的阈值操作 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。