opencv-041-基本阈值操作

知识点

API

1
2
3
4
5
6
7
8
9
10
11
12
13
double cv::threshold(
InputArray src,
OutputArray dst,
double thresh,
double maxval,
int type
)
其中type表示阈值分割的方法,支持如下五种:
THRESH_BINARY = 0 二值分割
THRESH_BINARY_INV = 1 反向二值分割
THRESH_TRUNC = 2 截断
THRESH_TOZERO = 3 取零
THRESH_TOZERO_INV = 4 反向取零

代码(c++,python)

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
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

/*
* 基本阈值操作
*/
int main() {
Mat src = imread("../images/master.jpg");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

int T = mean(src)[0];
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
for (int i = 0; i < 5; ++i) {
// THRESH_BINARY = 0
// THRESH_BINARY_INV = 1
// THRESH_TRUNC = 2
// THRESH_TOZERO = 3
// THRESH_TOZERO_INV = 4
threshold(gray, binary, T, 255, i);
imshow(format("binary_%d", i), binary);
}

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import cv2 as cv
import numpy as np
#
# THRESH_BINARY = 0
# THRESH_BINARY_INV = 1
# THRESH_TRUNC = 2
# THRESH_TOZERO = 3
# THRESH_TOZERO_INV = 4
#
src = cv.imread("D:/images/master.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

T = 127

# 转换为灰度图像
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
for i in range(5):
ret, binary = cv.threshold(gray, T, 255, i)
cv.imshow("binary_" + str(i), binary)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github