阈值(threshold):图像分割的标尺。
阈值类型:
阈值二值化(threshold binary)
阈值反二值化(threshold binary Inverted)
截断(truncate)
阈值取零(threshold to zero)
阈值反取零(threshold to zero Inverted)
实现代码如下:
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int threshold_max = 255;
int threshold_value = 127;
int type_value = 0;
int type_max = 4;
void Threshold_Demo(int, void*);
Mat src, dst, gray_src;
const char* output_title = "output image";
int main(int argc, char** argv) {
src = imread("D:\\sougou\\image\\1.jpg");
if (!src.data) {
printf("could not load image...\n");
return -1;
}
char input_image[] = "input image";
namedWindow(input_image, WINDOW_AUTOSIZE);
namedWindow("output image", WINDOW_AUTOSIZE);
imshow(input_image, src);
//cvtColor(src, dst, CV_BGR2GRAY);
//imshow("output image", dst);
createTrackbar("Threshold value:", output_title, &threshold_value, threshold_max, Threshold_Demo);
createTrackbar("Type value:", output_title, &type_value, type_max, Threshold_Demo);
Threshold_Demo(0, 0);
waitKey(0);
return 0;
}
void Threshold_Demo(int, void*) {
cvtColor(src, gray_src, CV_BGR2GRAY); //做阈值 图像必须为单通道、8位(灰度图像)
imshow("gray_image", gray_src);
/*
printf("%d\n", THRESH_BINARY);
printf("%d\n", THRESH_BINARY_INV);
printf("%d\n", THRESH_TRUNC);
printf("%d\n", THRESH_TOZERO);
printf("%d\n", THRESH_TOZERO_INV);
*/
threshold(gray_src, dst, threshold_value, threshold_max, type_value);
//threshold(gray_src, dst, threshold_value, threshold_max, THRESH_OTSU | type_value);//自动计算阈值 THRESH_TRIANGLE | type_value 也是自动算阈值
imshow(output_title, dst);
}
效果如下:
滑动type_value选择阈值类型(0-4,5中类型分别一一对应阈值二值化、阈值反二值化、截断、阈值取零、阈值反取零),滑动Threshold_value控制阈值大小。