opencv11_基本阈值操作

基本阈值操作

  • 图像阈值
  • 阈值类型
  • 代码演示

图像阈值(threshold)

  • 阈值 是什么?简单点说是把图像分割的标尺,这个标尺是根据什么产生的,阈值产生算法?阈值类型。(Binary segmentation)


阈值类型

  • 阈值二值化(threshold binary)
    • 下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值



  • 阈值反二值化(threshold binary Inverted)
    • 下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值



  • 截断 (truncate)
    • 下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值



  • 阈值取零 (threshold to zero)
    • 下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值



  • 阈值反取零 (threshold to zero inverted)
    • 下方的图表示图像像素点Src(x,y)值分布情况,蓝色水平线表示阈值



  • API

    使用THRESH_OTSUTHRESH_TRIANGLE时图像必须是八位的。

代码演示

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

#include <stdio.h>
#include "math.h"

using namespace cv;
Mat src, dst, gray;

int threshold_value = 127;
int threshold_max = 255;
String s[] = { "input", "output" };
int type_value = 2;
int type_max = 4;

void (int, void*);
int main(int argc, char** argv) {

src = imread("D:/documents/pictures/test.jpg");
if (!src.data) {
printf("could not openn");
return -1;
}

namedWindow(s[0], CV_WINDOW_AUTOSIZE);
namedWindow(s[1], CV_WINDOW_AUTOSIZE);
imshow(s[0], src);

createTrackbar("threshold value", s[1], &threshold_value, threshold_max, threshold_demo);
createTrackbar("type value", s[1], &type_value, type_max, threshold_demo);
threshold_demo(0, 0);

waitKey(0);
return 0;
}

void (int, void*) {
cvtColor(src, gray, CV_BGR2GRAY);

//THRESH_BINARY_INV 1
//THRESH_TRUNC 2
//THRESH_ZERO 3
//THRESH_ZERO_INV 4

threshold(gray, dst,threshold_value, threshold_max, type_value);
//threshold(gray, dst, 0, 255, THRESH_OTSU | type_value);//自动计算阈值
//threshold(gray, dst, 0, 255, THRESH_TRIANGLE | type_value);//三角形法计算阈值

imshow(s[1], dst);
}