opencv学习笔记(三)基本阈值处理操作

1.什么是阈值操作?

在这里插入图片描述
为了从一副图像中提取出我们需要的部分,应该用图像中的每一个像素点的灰度值与选取的阈值进行比较,并作出相应的判断。(注意:阈值的选取依赖于具体的问题。即:物体在不同的图像中有可能会有不同的灰度值。)

2.阈值化的类型:

OpenCV中提供了阈值函数:threshold()函数。函数作用:根据阈值和所选择的阈值化类型,将阈值上下的像素值分别置0或255实现二值化的效果。

函数原型: void threshold(InputArray src,OutputArray dst,double thresh,double maxval,int type)

参数说明

src:输入的源图像
dst:输出图像
thresh:阈值的大小
maxval:第五个参数的最大值
type:阈值化类型,可填入数字1~5.不同数字对应的阈值化类型:
在这里插入图片描述
1.THRESH_BINARY
在这里插入图片描述在这里插入图片描述
在运用该阈值类型的时候,先要选定一个特定的阈值量,比如:125,这样,新的阈值产生规则可以解释为大于125的像素点的灰度值设定为最大值(如8位灰度值最大为255),灰度值小于125的像素点的灰度值设定为0。

2.THRESH_BINARY_INV
在这里插入图片描述在这里插入图片描述
相当于第一个阈值化类型的取反。

3.THRESH_TRUNC
在这里插入图片描述 在这里插入图片描述
同样首先需要选定一个阈值,图像中大于该阈值的像素点被设定为该阈值,小于该阈值的保持不变。(例如:阈值选取为125,那小于125的阈值不改变,大于125的灰度值(230)的像素点就设定为该阈值)。

4.THRESH_TOZERO
在这里插入图片描述在这里插入图片描述
先选定一个阈值,然后对图像做如下处理:1 像素点的灰度值大于该阈值的不进行任何改变;2 像素点的灰度值小于该阈值的,其灰度值全部变为0。

5.THRESH_TOZERO_INV
在这里插入图片描述在这里插入图片描述
与第四个阈值化类型判断的情况相反。

3.基础阈值处理操作

实现代码

#include <opencv2/opencv.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include <iostream>
#include <math.h>
using namespace cv;
Mat src, gray_src, dst;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 1;
int type_max = 4;
const char* output_title = "binary image";
void Threshold_Demo(int, void*);
int main(int argc, char** argv) {
 src = imread("C:/Users/86159/Desktop/yasina.jpg");
 
 namedWindow("input image", WINDOW_AUTOSIZE);
 moveWindow("input image",50,0);
 namedWindow(output_title, WINDOW_AUTOSIZE);
 moveWindow(output_title, 800, 0);
 imshow("input image", src);
 
 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, COLOR_BGR2GRAY);
 threshold(src, dst, threshold_value, threshold_max,  type_value);	//阈值化函数
 imshow(output_title, dst);
}

效果如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

发布了3 篇原创文章 · 获赞 3 · 访问量 201

猜你喜欢

转载自blog.csdn.net/Rosen_er/article/details/104094454