阈值二值化:
设定一个临界值,将像素值大于临界值的像素设置成255,低于临界值设置成0。
CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
double thresh, double maxval, int type );
参数src:输入8位灰度图像,彩色图像会报错,无法运行
参数dst:输出二值图像
参数thresh:临界值
参数maxval:最大灰度值,255
参数type:阈值类型
在不知道具体阈值应该选择多少的情况下,type可以用THRESH_OTSU和THRESH_TRIANGLE,通过内部计算自动选择用、适应阈值。
threshold(gray_src, dst, threshold_value, threshold_max, type_value);
二值化:
反二值化:
截断:
取0:
反取0:
如果不知道具体应该选择阈值是多少的情况下,可以选择
threshold(gray_src, dst, 0, 255, THRESH_OTSU|type_value);
如果参数type仅为THRESH_OTSU,输出只有正常二值图。
若参数type为THRESH_OTSU|type_value,则可以选择不同方式下的自动阈值。
#include
#include
#include
using namespace std;
using namespace cv;
Mat src, dst, gray_src;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int type_max = 4;
char input_win[] = "inout image";
const char* output_win = "outputimage";
void ThreholdDemo(int, void*);
int main(int argc, char** argv)
{
src = imread("cat.jpg");
if (src.empty())
{
cout << "could not load image..." << endl;
return -1;
}
namedWindow(input_win, CV_WINDOW_AUTOSIZE);
namedWindow(output_win, CV_WINDOW_AUTOSIZE);
imshow(input_win, src);
createTrackbar("Threshold Value", output_win, &threshold_value, threshold_max, ThreholdDemo);
createTrackbar("type Value", output_win, &type_value, type_max, ThreholdDemo);
ThreholdDemo(0, 0);
waitKey(0);
return 0;
}
void ThreholdDemo(int, void*)
{
cvtColor(src, gray_src, CV_BGR2GRAY);
threshold(gray_src, dst, threshold_value, threshold_max, type_value);
//threshold(gray_src, dst, 0, 255, THRESH_OTSU | type_value);
imshow(output_win, dst);
}