系统 | Ubuntu 18.04 |
---|---|
OpenCV 版本 | 4.5.1 |
接口类型 | C++ |
安装OpenCV | 点我安装 |
文章目录
低级图像处理: 对图像某个像素进行处理
高级图像处理: 对图像像素之间的联系进行处理
一、阈值化操作
利用图像中的物体和背景之间的灰度差异作为分割,在灰度差异之间设置一个阈值,这属于像素级的分割。
1.1 基本的阈值操作
src ( x , y ) \text{src}(x,y) src(x,y)为输入像素点, dst ( x , y ) \text{dst}(x,y) dst(x,y)为输出像素点, thresh \text{thresh} thresh为阈值。
0为黑,255为白。
阈值类型:
-
二值化
cv::THRESH_BINRY
d s t ( x , y ) = { 255 若 src ( x , y ) > thresh 0 其他 dst(x,y)=\begin{cases} 255 & \text{ 若 } \text{src}(x,y)>\text{thresh} \\ 0 & \text{ 其他 } \end{cases} dst(x,y)={ 2550 若 src(x,y)>thresh 其他
阈值增大,图像由白变黑。 -
反二值化
cv::THRESH_BINRY_INV
d s t ( x , y ) = { 0 若 src ( x , y ) > thresh 255 其他 dst(x,y)=\begin{cases} 0 & \text{ 若 } \text{src}(x,y)>\text{thresh} \\ 255 & \text{ 其他 } \end{cases} dst(x,y)={ 0255 若 src(x,y)>thresh 其他
阈值增大,图像由黑变白。 -
截断
cv::THRESH_TRUNC
d s t ( x , y ) = { thresh 若 src ( x , y ) > thresh src ( x , y ) 其他 dst(x,y)=\begin{cases} \text{thresh} & \text{ 若 } \text{src}(x,y)>\text{thresh} \\ \text{src}(x,y) & \text{ 其他 } \end{cases} dst(x,y)={ threshsrc(x,y) 若 src(x,y)>thresh 其他
阈值增大,图像由黑变原像素。 -
反置0
cv::THRESH_TOZERO_INV
d s t ( x , y ) = { src ( x , y ) 若 src ( x , y ) > thresh 0 其他 dst(x,y)=\begin{cases} \text{src}(x,y) & \text{ 若 } \text{src}(x,y)>\text{thresh} \\ 0 & \text{ 其他 } \end{cases} dst(x,y)={ src(x,y)0 若 src(x,y)>thresh 其他
阈值增大,图像由原像素变黑。 -
置0
cv::THRESH_TOZERO
d s t ( x , y ) = { 0 若 src ( x , y ) > thresh src ( x , y ) 其他 dst(x,y)=\begin{cases} 0 & \text{ 若 } \text{src}(x,y)>\text{thresh} \\ \text{src}(x,y) & \text{ 其他 } \end{cases} dst(x,y)={ 0src(x,y) 若 src(x,y)>thresh 其他
阈值增大,图像由黑变原像素。
代码实现
- 代码(cpp)
mkdir Threshold && cd Threshold
touch threshold.cpp && gedit threshold.cpp
拷贝下列代码
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdlib.h>
#include <stdio.h>
#include <opencv2/imgproc/types_c.h>
using namespace cv;
int threshold_value = 0;
int threshold_type = 3;
int const max_value = 255;
int const max_type = 4;
int const max_BINRY_value = 255;
Mat src,src_gray,dst;
char* window_name = "Threshold Demo";
//两个滚动条的标签
char* trackbar_type = "阈值类型: \n 0: 二值化 \n 1: 反二值化 \n 2: 截断 \n 3: 反置零 \n 4: 置零";
char* trackbar_value = "阈值";
void Threshold_Demo(int, void*);