图像阈值 threshold
- 是把图像分割的标尺
- 应用举例:从一副图像中利用阈值分割出我们需要的物体部分(当然这里的物体可以是一部分或者整体)。这样的图像分割方法是基于图像中物体与背景之间的灰度差异,而且此分割属于像素级的分割。
- 为了从一副图像中提取出我们需要的部分,应该用图像中的每一个像素点的灰度值与选取的阈值进行比较,并作出相应的判断。(注意:阈值的选取依赖于具体的问题。即:物体在不同的图像中有可能会有不同的灰度值。
阈值类型(阈值处理方法)----threshold_type
阈值二值化(threshold binary):超过阈值的取最大值,小于阈值的取最小值
阈值反二值化(threshold binary inverted):超过阈值的取最小值,小于阈值的取最大值
阈值截断(truncate):超过阈值的,等于阈值
阈值取零(threshold to zero):小于阈值的,取零
阈值反取零(threshold to zero inverted):大于阈值的,取零
阈值寻找方法
THRESH_OTSU:当图像黑白分明时可以使用
THRESH_TRIANGLE
这两个类型与前面五个结合起来用,不用自己指定thresh值,系统会进行计算并且作为返回值返回
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
const char result[] = "optput_image";
int thresh_value = 127;
int thresh_max = 255;
int type = 2;
int type_max = 4;
void threshold_demo(int,void *);
Mat src,dst;
int main(int argc,char** argv)
{
src = imread("D:/vcprojects/test.png");
if (!src.data)
{
printf("could not load image...\n");
return -1;
}
namedWindow("input_image", WINDOW_AUTOSIZE);
namedWindow(result, WINDOW_AUTOSIZE);
imshow("input_image", src);
createTrackbar("thresh:", result, &thresh_value, thresh_max, threshold_demo);
createTrackbar("type:", result, &type, type_max, threshold_demo);//用于控制thresh_type的控件
threshold_demo(0, 0);
waitKey(0);
return 0;
}
void threshold_demo(int, void *)
{
Mat gray_image;
cvtColor(src, gray_image, COLOR_BGR2GRAY);
//threshold(gray_image, dst, thresh_value, thresh_max, type);//在opencv中阈值类型应该是有默认序号的
threshold(gray_image, dst, 0, 255,THRESH_OTSU|type );//使用ostu生成阈值,会忽略我们自己设定的阈值,并且滑动控件时,也不会改变
imshow(result, dst);
}
结果