阈值:
- 最简单的分割方法
- 应用示例:分离对应于我们想要分析的对象的图像的区域。该分离基于对象像素和背景像素之间的强度变化。
- 为了区分我们感兴趣的像素(其最终将被拒绝),我们对每个像素强度值相对于阈值进行比较(根据要解决的问题确定)。
- 一旦我们正确分离了重要的像素,我们可以用一个确定的值来设置它们来识别它们(即我们可以为它们分配值(黑色),(白色)或适合您需要的任何值)。
如下图的分割:
阈值类型:
左下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值:
阈值二值化(threshold binary)
阈值反二值化(threshold binary Inverted)
截断 (truncate)
阈值取零 (threshold to zero)
阈值反取零 (threshold to zero inverted)
对应的参数值:
// opencv0015.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int threshold_value = 0;
int threshold_type = 3;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;
Mat src, src_gray, dst;
const char* window_name = "Threshold Demo";
const char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
const char* trackbar_value = "Value";
void Threshold_Demo(int ,void*);
int main()
{
string imageName = "D:/images/666.jpg";
src = imread(imageName,IMREAD_COLOR); //读取一个图片
if (src.empty())
{
cout << "load image failed" << endl;
return -1;
}
cvtColor(src, src_gray, COLOR_BGR2GRAY); //装换成灰色图像
namedWindow(window_name,WINDOW_AUTOSIZE);
createTrackbar(trackbar_type, window_name, &threshold_type, max_type, Threshold_Demo); //选择阈值类型
createTrackbar(trackbar_value, window_name, &threshold_value, max_value, Threshold_Demo); //选择阈值的值
Threshold_Demo(0,0);
waitKey(0);
return 0;
}
void Threshold_Demo(int, void *)
{
/* 0: Binary
1: Binary Inverted
2: Threshold Truncated
3: Threshold to Zero
4: Threshold to Zero Inverted
*/
threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);
imshow(window_name, dst);
}
简单介绍一下函数:
threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);
- src_gray 输入图像,这里是灰度图像,你可以使用原图像,效果有些不同
- dst 输出图像
- threshold_value 当前输入的阈值,这个根据情况来选择 0~255;
- max_BINARY_value,设置阈值的最大值;
- threshold_type 阈值的种类,上边有明细。
那我们看看结果吧:
截断:
阈值二值化与反向二值化:
阈值与零与倒置
是不是非常的简单,喜欢的话就一起来学习吧,可以关注我的博客,一起成长与进步吧。