Opencv學習筆記(八)閾值化

2021-10-09 06:34:23 字數 2495 閱讀 5081

閾值化函式就是指當影象某點的畫素值高於或者低於某乙個值(閾值)時統一取一值,其他時候保持不變或者變為0.通過這一方法我們可以從一張中得到我我們想要的部分,前提是該部分與背景灰度值有較大的差異。這一過程可以通過opnecv中的函式thresold()函式和adaptivethreshold()函式實現。

threshold

( inputarray src, outputarray dst,

double thresh,

double maxval,

int type )

;

一、二個引數是輸入輸出影象,有意思的是並不如原始碼注釋裡寫的一樣要求為8位單通道影象,事實上cv_8uc3即八位三通道彩圖也可正常執行,相當於是對每個通道分別閾值化操作;

第三個引數是閾值;

第四個引數是可能會使用到的原畫素替換值,具體替換方式見引數type中介紹;

第五個引數給出了閾值化的型別:

thresh_binarydst

(x,y

)=

maxval &\text \\0&\text\end

dst(x,

y)= 0 &\text \\maxval&\text\end

dst(x,

y)= thresh &\text \\src(x,y)&\text\end

dst(x,

y)= src(x,y) &\text \\0&\text\end

dst(x,

y)= 0 &\text \\src(x,y)&\text\end

dst(x,

y)=//cvtcolor(srcimg, srcimg, color_rgb2gray);

1 / 255.0); //需要使用尺度變換因子1/255才可正常顯示

imshow

("原始"

, srcimg)

; mat dstimg =mat::zeros (srcimg.

size()

, srcimg.

type()

);threshold

(srcimg, dstimg,

0.6,1,

0);imshow

("閾值化"

, dstimg)

;waitkey(0

);return1;

}自適應閾值化函式是指閾值不固定,而是隨著處理點變化而變化的,這樣就可以針對於亮度分布差異較大的影象進行部分提取,閾值會隨著區域亮度分布,閾值的確定有均值確定和高斯卷積結果確定兩種,opencv中函式原型如下:

adaptivethreshold

( inputarray src, outputarray dst,

double maxvalue,

int adaptivemethod,

int thresholdtype,

int blocksize,

double c )

;

一、二個引數為輸入輸出影象,這裡就要求是單通道了,多通道影象無法執行,而且如果輸入影象為浮點型也會報錯;

第三個引數是可能會使用到的原畫素替換值,具體替換方式見引數thresholdtype中介紹;

第四個引數為閾值的確定方式,有adaptive_thresh_gaussian_c、adaptive_thresh_mean_c兩種,前者即為高斯卷積確定,通過高斯卷積核與待計算參考點區域卷積所得結果減去第七個引數即為該點的閾值;後者為均值確定,通過計算參考點區域內均值減去第七個引數得到該點閾值;

第五個引數為閾值化方式,可選有thresh_binarythresh_binary_inv;

第六個引數為矩形窗的大小,應該取計數值,像是5,7,11;

第七個引數為閾值的偏置;

示例**:

int

main()

cvtcolor

(srcimg, srcimg, color_rgb2gray)

; 1 / 255.0); //需要使用尺度變換因子1/255才可正常顯示

imshow

("原始"

, srcimg)

; mat dstimg =mat::zeros (srcimg.

size()

, srcimg.

type()

);adaptivethreshold

(srcimg, dstimg,

255, adaptive_thresh_mean_c,0,

5,0)

;imshow

("閾值化"

, dstimg)

;waitkey(0

);return1;

}

參考文獻

閾值化操作——threshold()與adaptivethreshold()

OpenCV學習筆記 自適應閾值化

自適應閾值化的函式為 自適應閾值方法 void cvadaptivethreshold const cvarr src,cvarr dst,double max value,int adaptive method cv adaptive thresh mean c,int threshold typ...

OpenCV學習筆記 自適應閾值化

自適應閾值化的函式為 自適應閾值方法 void cvadaptivethreshold const cvarr src,cvarr dst,double max value,int adaptive method cv adaptive thresh mean c,int threshold typ...

opencv學習筆記 閾值分割

先選定乙個特定的閾值量,比如 127 新的閾值產生規則為 dst x,y maxval quad if quad src x,y thresh 0,otherwise end dst x,y 0 quad if quad src x,y thresh maxval,otherwise end dst...