在opencv中对图片的阀值操作其实是对图片灰度的选择与处理,首先选择一个阀值,大于这个值的灰度会怎么处理,小于这个值的灰度又会怎么处理。在opencv中已经给出了基本的五种处理方式,分别对应了五种不同对灰度值的操作。
阀值的操作用到的函数为:threshold() ;
一、五种处理方式:
1.二进制阀值化(type =1)
意思是灰度值大于阀值的变为maxVal,否则变为0(黑色)。
2.反二进制阀值化(type =2)
意思是灰度值大于阀值的变为0(黑色),否则变为maxVal。
3.截断阀值化(type =3)
意思是灰度值大于阀值的变为阀值,否则不变。
4.阀值化为0(type =4)
意思是灰度值大于阀值的不变,否则变为0(黑色)。
5.反阀值化为0(type =5)
意思是灰度值大于阀值的变为0(黑色),否则不变。
二、以上为五种处理方式,接下来是 threshold() 函数的具体应用。
threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type );
src:原图像
dst:输出图像
thresh:设置的阀值
maxval:设置的最大值
type:处理方式类型,以上的五种
三、具体代码
//输出图片
Mat src_gray,dst_1,dst_2,dst_3,dst_4,dst_5;
Mat src = imread ("E:\\desk.jpg");
//图片灰度化
cvtColor (src,src_gray,COLOR_BGR2GRAY);
//阀值化
cv::threshold (src_gray,dst_1,125,255,1);
cv::threshold (src_gray,dst_2,125,255,2);
cv::threshold (src_gray,dst_3,125,255,3);
cv::threshold (src_gray,dst_4,125,255,4);
cv::threshold (src_gray,dst_5,125,255,5);
//显示图片
imshow ("out",src_gray);
imshow ("out1",dst_1);
imshow ("out2",dst_2);
imshow ("out3",dst_3);
imshow ("out4",dst_4);
imshow ("out5",dst_5);
waitKey ();
四、结果
原图灰度图像:
处理方式1—5的结果分别为: