实现opencv阈值操作函数threshold

理论部分已经在这篇opencv自带例子学习-灰度图像的阈值操作解释过,这里就不再赘述了。

下面直接贴代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//灰度的阈值变换,实现opencv的threshold函数
#include<opencv2/opencv.hpp>
#include<iostream>
#include<cassert>

namespace mycv {
enum ThresholdType
{
//详情参考https://docs.opencv.org/3.4.3/d7/d1b/group__imgproc__misc.html#gaa9e58d2860d4afa658ef70a9b1115576
THRESH_BINARY = 0,
THRESH_BINARY_INV = 1,
THRESH_TRUNC = 2,
THRESH_TOZERO = 3,
THRESH_TOZERO_INV = 4
};
void threshold(cv::Mat& input, cv::Mat& output, const uchar thresh = 128, const uchar max_val = 255, int type = 0);

}//mycv

int main()
{
cv::Mat img = cv::imread("lena.jpg", 0);
if (img.empty()) return -1;
cv::Mat dst;

mycv::threshold(img, dst);
cv::imwrite("dst.bmp", dst);
cv::imshow("img", img);
cv::imshow("dst", dst);
cv::waitKey(0);

return 0;
}

void mycv::threshold(cv::Mat& input, cv::Mat& output, const uchar thresh, const uchar max_val, int type)
{
assert(1 == input.channels());
output = input.clone();
const int rows = input.rows;//行
const int cols = input.cols;//列

switch (type)//五种操作方式
{
case 0:
for(int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
{
//THRESH_BINARY
if (input.at<uchar>(i, j) > thresh)
output.at<uchar>(i, j) = max_val;
else
output.at<uchar>(i, j) = 0;
}
break;
case 1:
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
{
//THRESH_BINARY_INV
if (input.at<uchar>(i, j) < thresh)
output.at<uchar>(i, j) = max_val;
else
output.at<uchar>(i, j) = 0;
}
break;
case 2:
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
{
//THRESH_TRUNC
if (input.at<uchar>(i, j) > thresh)
output.at<uchar>(i, j) = thresh;
else
output.at<uchar>(i, j) = input.at<uchar>(i, j);
}
break;
case 3:
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
{
//THRESH_TOZERO
if (input.at<uchar>(i, j) < thresh)
output.at<uchar>(i, j) = input.at<uchar>(i, j);
else
output.at<uchar>(i, j) = 0;
}
break;
case 4:
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
{
//THRESH_TOZERO_INV
if (input.at<uchar>(i, j) > thresh)
output.at<uchar>(i, j) = input.at<uchar>(i, j);
else
output.at<uchar>(i, j) = 0;
}
break;
default:
assert(false);
}
}//threshold
-------------本文结束感谢您的阅读-------------