阈值化算法(使用滑动条)
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
#define WINDOW_NAME "【程序窗口】"
int g_nThresholdValue = 100;
int g_nThresholdType = 3;
Mat g_srcImage, g_grayImage, g_dstImage;
void on_Threshold(int, void*);//回调函数
int main() {
g_srcImage = imread("001.png");
if (!g_srcImage.data) {
cout << "读取图片错误!" << endl;
return false;
}
cvtColor(g_srcImage, g_grayImage, COLOR_RGB2GRAY);
namedWindow(WINDOW_NAME, WINDOW_AUTOSIZE);
imshow(WINDOW_NAME, g_srcImage);
createTrackbar("模式", WINDOW_NAME, &g_nThresholdType, 4, on_Threshold);
createTrackbar("参数值", WINDOW_NAME, &g_nThresholdValue, 255, on_Threshold);
on_Threshold(0, 0);
while (1) {
int key;
key = waitKey(20);
if ((char)key == 27)
break;
}
return 0;
}
//on_Threshold函数
void on_Threshold(int, void*) {
threshold(g_grayImage, g_dstImage, g_nThresholdValue, 255, g_nThresholdType);
imshow(WINDOW_NAME, g_dstImage);
}
固定值
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
#define WINDOW_NAME "【程序窗口】"
int g_nThresholdValue = 200;
int g_nThresholdType = 3;
Mat g_srcImage, g_grayImage, g_dstImage;
void on_Threshold(int, void*);//回调函数
int main() {
g_srcImage = imread("goal1.png");
if (!g_srcImage.data) {
cout << "读取图片错误!" << endl;
return false;
}
cvtColor(g_srcImage, g_grayImage, COLOR_RGB2GRAY);
//创建窗口并显示原图
namedWindow(WINDOW_NAME, WINDOW_AUTOSIZE);
imshow(WINDOW_NAME, g_srcImage);
threshold(g_grayImage, g_dstImage, g_nThresholdValue, 255, g_nThresholdType);
imshow(WINDOW_NAME, g_dstImage);
imwrite("mask.png", g_dstImage);
waitKey(200000);
return 0;
}