C++阈值分割
1、阈值分割
- 5种类型的阈值分割如下:
第一种:阈值二值化
蓝色线表示阈值
原理:像素值大于阈值时,为最大值,小于阈值则为0。
第二种:阈值反二值化
原理:像素值大于阈值时,为0,否则为设定的最大值。
第三种:截断
原理:像素值大于阈值时,为设定的阈值,否则为像素值本身。
第四种:阈值取零
原理:像素值大于阈值时,为像素值,否则为0.
第五种:阈值反取零
原理:像素值大于阈值时,为0,否则为像素值本身。
2、代码实现
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
void CallbackFunc(int, void*);
Mat img, gray, dst;
int threshold_num = 2;
int element = 127;
int max_size = 255;
int threshlod_classes = 4;
void CallbackFunc(int, void*);
int main(int argc, char** argv)
{
img = imread("G:/testpic/img.png");
if (!img.data)
{
printf("cannot load the image");
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", img);
namedWindow("output", WINDOW_AUTOSIZE);
createTrackbar("thresh type:", "output", &threshold_num, threshold_classes, CallbackFunc);
createTrackbar("num:", "output", &element, max_size, CallbackFunc);
waitKey(0);
return 0;
}
void CallbackFunc(int, void*)
{
cvtColor(img, gray, COLOR_BGR2GRAY);
//阈值分割
threshold(gray, dst, element, max_size, threshold_num);
imshow("output", dst);
return;
}