opencv-042-图像二值寻找算法(OTSU)

知识点

图像二值化,除了我们上次分享的手动阈值设置与根据灰度图像均值的方法之外,还有几个根据图像直方图实现自动全局阈值寻找的方法,OpenCV中支持的有OTSU与Triangle两种直方图阈值寻找算法。其中OTSU的是通过计算类间最大方差来确定分割阈值的阈值选择算法,OTSU算法对直方图有两个峰,中间有明显波谷的直方图对应图像二值化效果比较好,而对于只有一个单峰的直方图对应的图像分割效果没有双峰的好。

OpenCV中OTSU算法使用只需要在threshold函数的type类型声明THRESH_OTSU即可.

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

using namespace std;
using namespace cv;

/*
* 图像二值寻找算法 – OTSU
*/
int main() {
Mat src = imread("../images/test.png");
if (src.empty()) {
cout << "could not load image.." << endl;
}
imshow("input", src);

// 自动阈值寻找与二值化
Mat gray, binary;
cvtColor(src, gray, COLOR_BGR2GRAY);
double T = threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
cout << "threshold : " << T << endl;
imshow("binary", 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
24
25
26
27
28
29
30
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/lena.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
h, w = src.shape[:2]

# 自动阈值分割 OTSU
gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
print("ret :", ret)
cv.imshow("binary", binary)

result = np.zeros([h, w*2, 3], dtype=src.dtype)
result[0:h,0:w,:] = src
result[0:h,w:2*w,:] = cv.cvtColor(binary, cv.COLOR_GRAY2BGR)
cv.putText(result, "input", (10, 30), cv.FONT_ITALIC, 1.0, (0, 0, 255), 2)
cv.putText(result, "binary, threshold = " + str(ret), (w+10, 30), cv.FONT_ITALIC, 1.0, (0, 0, 255), 2)
cv.imshow("result", result)
cv.imwrite("D:/binary_result.png", result)

cv.waitKey(0)
cv.destroyAllWindows()

结果

代码地址

github