15-基本阈值操作

掌握

1、图像阈值;
2、阈值类型;
3、代码演示;

图像阈值(threshold)

1、图像阈值:图像分割的标尺,阈值的确定由阈值产生算法决定(OpenCV提供了2种阈值产生算法);阈值分割(threshold segmentation)
2、阈值分为不同的类型,类型1:阈值二值化(threshold binary),原理如下:
在这里插入图片描述3、类型2:阈值反二值化(threshold binary Inverted)
在这里插入图片描述4、类型3:阈值截断(truncate)
在这里插入图片描述5、类型4:阈值取零(threshold to zero):
在这里插入图片描述6、类型5:阈值反取零(threshold to zero inverted):大于时取0,小于时不变
在这里插入图片描述

相关API

1、阈值转换API:threshold():
在这里插入图片描述注:
OpenCV提供了两种根据图像自动寻找阈值的宏定义:这两种宏只支持8位单通道图像

//产生阈值的宏
THRESH_OTSU;
THRESH_TRIANGLE;  //三角法取阈值(根据灰度直方图计算)

阈值类型在OpenCV中的宏定义:

THRESH_BINARY;
THRESH_BINARY_INV;
THRESH_TRUNC;
THRESH_TOZERO;
THRESH_TOZERO_INV;  //反取0阈值

在这里插入图片描述

Code

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

Mat src,gray_src ,dst;
int threshold_value = 127; //设定一个初始阈值
int threshold_max = 255;  
const char* output_title = "binary image";

int type_value = 2;
int type_max = 4;

void Threshold_Demo(int, void*);

int main(int argc, char** argv)
{
	src = imread("C:\\Users\\hello\\Desktop\\2.jpg");
	if (!src.data)
	{
		cout << "could not load the image..." << endl;
		return -1;
	}
	namedWindow("input image", CV_WINDOW_AUTOSIZE);
	namedWindow(output_title, CV_WINDOW_AUTOSIZE);
	imshow("input image", src);

	//创建滑动条1 --改变灰度值
	createTrackbar("Threshold Value:", output_title, &threshold_value, threshold_max, Threshold_Demo);
	//创建滑动条2 --改变阈值类型
	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); //转换为灰度图像
	
	printf("%d", THRESH_BINARY);  //0
	printf("%d", THRESH_BINARY_INV);//1
	printf("%d", THRESH_TRUNC);//2
	printf("%d", THRESH_TOZERO);//3
	printf("%d", THRESH_TOZERO_INV);//4
	//threshold(gray_src, dst, threshold_value, threshold_max, THRESH_BINARY);  //二值化
	//threshold(gray_src, dst, threshold_value, threshold_max, THRESH_BINARY_INV);  //反二值化
	threshold(gray_src, dst, threshold_value, threshold_max, THRESH_OTSU |type_value);  //自动计算阈值,此时手动更改阈值不起作用
	threshold(gray_src, dst, threshold_value, threshold_max, type_value);  //自动计算阈值
	imshow(output_title, dst);
}

Consequence

阈值二值化:
在这里插入图片描述
阈值反二值化:
在这里插入图片描述
阈值截断:
在这里插入图片描述
阈值取零:
在这里插入图片描述
阈值反取零:
在这里插入图片描述
自动计算阈值:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值