前言
上一篇文章,我们讲解了图像处理中的亮度和对比度的变化,这篇文章我们来做一个阈值函数。
最简单的图像分割方法
阈值是最简单的图像分割方法。
比如为了从下图中分割出苹果,我们利用前景与背景的灰度差值,通过设定一个阈值,对于该像素大于这个阈值时就以黑色表示,小于便以灰色表示。

五种阈值类型
和OpenCV一样,我们将提供五种阈值类型,方便使用。
下面是原图像的波形表示,纵坐标表示像素点的灰度值大小,蓝线是阈值大小。

二进制阈值化
公式表示是:

图像表示是:

可见超过该阈值的就变成最大值(即255),否则变成最小值(也就是0)。我们需要一个函数来实现这个功能:
代码如下:
var CV_THRESH_BINARY = function(__value, __thresh, __maxVal){
return __value > __thresh ? __maxVal : 0;
};
反二进制阈值化
公式表示是:

图像表示是:

这个则反过来,超过阈值的变成最小值,否则变成最大值。函数实现是:
代码如下:
var CV_THRESH_BINARY_INV = function(__value, __thresh, __maxVal){
return __value > __thresh ? 0 : __maxVal;
};
截断阈值化
公式表示是:

图像表示是:

可见这个是超过阈值的就被截断。函数实现是:
代码如下:
var CV_THRESH_TRUNC = function(__value, __thresh, __maxVal){
return __value > __thresh ? __thresh : 0;
};
阈值化为0
公式表示是:

图像表示是:

这个则是小于阈值的都化为0处理。函数实现:
代码如下:
var CV_THRESH_TOZERO = function(__value, __thresh, __maxVal){
return __value > __thresh ? __value : 0;
};
反阈值化为0
公式表示是:

图像表示是:

这个则在超过阈值时候置为0,函数实现是:
代码如下:
var CV_THRESH_TOZERO_INV = function(__value, __thresh, __maxVal){
return __value > __thresh ? 0 : __value;
};
阈值处理函数实现
然后我们做一个函数对整幅图进行上面这几种类型的阈值处理。
代码如下:
var threshold = function(__src, __thresh, __maxVal, __thresholdType, __dst){
(__src && __thresh) || error(arguments.callee, IS_UNDEFINED_OR_NULL/* {line} */);
if(__src.type && __src.type == "CV_GRAY"){
var width = __src.col,
height = __src.row,
sData = __src.data,
dst = __dst || new Mat(height, width, CV_GRAY),
dData = dst.data,
maxVal = __maxVal || 255,
threshouldType = __thresholdType || CV_THRESH_BINARY;
var i, j, offset;
for(i = height; i--;){
for(j = width; j--;){
offset = i * width + j;
dData[offset] = threshouldType(sData[offset], __thresh, maxVal);
}
}
}else{
error(arguments.callee, UNSPPORT_DATA_TYPE/* {line} */);
}
return dst;
};
这个函数比较简单,就是对每个像素点赋值为
代码如下:
threshouldType(sData[offset], __thresh, maxVal)
返回的数值。