📢:如果你也对机器人、人工智能感兴趣,看来我们志同道合✨
📢:不妨浏览一下我的博客主页【https://blog.csdn.net/weixin_51244852】
📢:文章若有幸对你有帮助,可点赞 👍 收藏 ⭐不迷路🙉
📢:内容若有错误,敬请留言 📝指正!原创文,转载请注明出处
一、基本阈值操作
阈值(threshold):图像分割的标尺,本次关于阈值的操作就是在之前学过的二值化基础上,对函数threshold的最后一个参数的研究。
二、API-threshold
图像的阈值操作函数原型如下:
double threshold( InputArray src, OutputArray dst, double thresh, double maxval,int type);
函数参数含义如下:
(1)InputArray类型的src ,输入图像,多通道、8位或32位浮点。
(2)OutputArray类型的dst ,输出图像,图像的大小、类型、通道数和输入图像相同。
(3)double类型的thresh,阈值。
(4)double类型的maxval,使用THRESH_BINARY 和THRESH_BINARY_INV阈值类型时候的最大值。
(5)int类型的type,阈值类型,取值参见:cv::ThresholdTypes,根据阈值进行分割,其方法包括:
1.二值化
2.反二值化
3.截断
4.阈值取零:小于阈值的像素取零
5.阈值反取零
三、部分代码-单滑动条
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat src, dst;
void Threshold_Demo(int typeValue, void*)
{
cvtColor(src, dst, COLOR_BGR2GRAY);
threshold(dst, dst, 127, 255, typeValue);
imshow("二值化图像", dst);
}
int main(){
src = imread("D:/images/lena.png");
if (src.empty())
{
cout << "could not load image..." << endl;
return -1;
}
imshow("原图", src);
int a = 1;
Threshold_Demo(0, 0);
createTrackbar("Type Value", "二值化图像", &a, 4, Threshold_Demo);
waitKey(0);
return 0;
}
四、全部代码-双滑动条
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace std;
using namespace cv;
//全局变量,主函数外的变量
Mat src, dst;
int thresholdValue = 127;
int thresholdMax = 255;
int typeValue = 2;
int typeMax = 4;//对应5种阈值分割的方法
const char* output_title = "binary img";//窗口名称“二值化图像”
//定义Threshold_Demo函数,用于图像的阈值
void Threshold_Demo(int, void*)
{
threshold(src, dst, thresholdValue, thresholdMax, typeValue);
imshow(output_title, dst);
}
//主函数入口
int main()
{
src = imread("D:/images/lena.png");
if (src.empty())
{
cout << "could not load image..." << endl;
return -1;
}
imshow("原图", src);
namedWindow(output_title, WINDOW_AUTOSIZE);
createTrackbar("Threshold Value", output_title, &thresholdValue, thresholdMax, Threshold_Demo);//动态调整
createTrackbar("Type Value", output_title, &typeValue, typeMax, Threshold_Demo);
//调用Threshold_Demo函数
Threshold_Demo(0, 0);
imshow(output_title, dst);
waitKey(0);
return 0;
}