歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> OpenCV實現圖像的灰度處理,二值化,閥值選擇

OpenCV實現圖像的灰度處理,二值化,閥值選擇

日期:2017/3/1 9:38:16   编辑:Linux編程

前幾天接觸了圖像的處理,發現用OPencv處理確實比較方便,畢竟是很多東西都封裝好的,但是要研究裡面的東西,還是比較麻煩的,首先,你得知道圖片處理的一些知識,比如腐蝕,膨脹,仿射,透射等,還有很多算法,傅裡葉,積分,卷積,頻譜,加權。反正我看了半天,是雲裡霧裡的,所以就想先就籠統的過一遍,以後遇到了再具體分析,比較這方面的基礎沒那麼扎實。先來記錄下目前學習到的一些知識。

首先是圖像的灰度處理:

CV_LOAD_IMAGE_GRAYSCALE,這是最簡單之間的辦法,在載入圖像時直接處理

IplImage* Igray=cvLoadImage("test.jpg",CV_LOAD_IMAGE_GRAYSCALE);

得到的圖像就是單通道的,也可以用這個函數:CVAPI(void) cvCvtColor( const CvArr* src, CvArr* dst, int code );

code=CV_BGR2GRAY;

opencv還提供了很多方式,我這邊就不一一舉例了。

圖像的二值化是將圖像上的像素點的灰度值設置為0或255,也就是將整個圖像呈現出明顯的黑白效果。

灰度處理後就可以二值化了,這是方便圖像處理的重要步驟,但貌似不適合對顏色有要求的圖像處理,對輪廓有要求的比較有效。

函數是這個:CVAPI(double) cvThreshold( const CvArr* src, CvArr* dst,
double threshold, double max_value,
int threshold_type );

threshold是閥值,max_value取值255最大值

threshold_type:就是顯示的輪廓會有不同

/* Types of thresholding */
#define CV_THRESH_BINARY 0 /* value = value > threshold ? max_value : 0 */
#define CV_THRESH_BINARY_INV 1 /* value = value > threshold ? 0 : max_value */
#define CV_THRESH_TRUNC 2 /* value = value > threshold ? threshold : value */
#define CV_THRESH_TOZERO 3 /* value = value > threshold ? value : 0 */
#define CV_THRESH_TOZERO_INV 4 /* value = value > threshold ? 0 : value */
#define CV_THRESH_MASK 7

#define CV_THRESH_OTSU 8 /* use Otsu algorithm to choose the optimal threshold value;
combine the flag with one of the above CV_THRESH_* values */

閥值選取

一般來說會取100,127等固定值,這類取值比較隨意,的到的圖像也還可以,但是這邊比較推薦的一個方式是自適應閥值:

IplImage* Igray=0,*It=0,*Iat;


int threshold_type = CV_THRESH_BINARY;
int adaptive_method = CV_ADAPTIVE_THRESH_GAUSSIAN_C;
int blocksize = 31;
double offset =15;
int threshold=100;
if(0==(Igray=cvLoadImage("test.jpg",CV_LOAD_IMAGE_GRAYSCALE))){
return -1;
}
It = cvCreateImage(cvSize(Igray->width,Igray->height),
IPL_DEPTH_8U,
1);
Iat = cvCreateImage(cvSize(Igray->width,Igray->height),
IPL_DEPTH_8U,
1);

//Threshold
cvThreshold(Igray,It,threshold,255,threshold_type);//閥值100
cvAdaptiveThreshold(Igray,Iat,255,adaptive_method,//自適應閥值,blocksize為奇數
threshold_type,blocksize,offset);

--------------------------------------分割線 --------------------------------------

Ubuntu Linux下安裝OpenCV2.4.1所需包 http://www.linuxidc.com/Linux/2012-08/68184.htm

Ubuntu 12.04 安裝 OpenCV2.4.2 http://www.linuxidc.com/Linux/2012-09/70158.htm

CentOS下OpenCV無法讀取視頻文件 http://www.linuxidc.com/Linux/2011-07/39295.htm

Ubuntu 12.04下安裝OpenCV 2.4.5總結 http://www.linuxidc.com/Linux/2013-06/86704.htm

Ubuntu 10.04中安裝OpenCv2.1九步曲 http://www.linuxidc.com/Linux/2010-09/28678.htm

基於QT和OpenCV的人臉識別系統 http://www.linuxidc.com/Linux/2011-11/47806.htm

--------------------------------------分割線 --------------------------------------

OpenCV的詳細介紹:請點這裡
OpenCV的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved