图像的二值化就是将图像上的像素点的灰度值设置为0或255,这样将使整个图像呈现出明显的黑白效果。在数字图像处理中,二值图像占有非常重要的地位,图像的二值化使图像中数据量大为减少,从而能凸显出目标的轮廓。OpenCV中提供了函数cv::threshold();

函数:

1
2
double threshold( InputArray src, OutputArray dst,  
double thresh, double maxval, int type );

参数说明:

src:源图像。可以为8位的灰度图,也可以为32位的彩色图像。只是输出
dst:输出图像。根据源图像的位数不同,输出也不同。
thresh:阈值
maxval:dst图像中最大值
type:阈值类型,可以具体类型如下:

测试代码:

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
#!/usr/bin/python
# coding=utf-8

import cv2
from matplotlib import pyplot as plt

import numpy as np

threshold = 10

img = cv2.imread('pictures/picture.jpeg')
origin = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)  # 将图像转换为RGB格式 原因:matplotlib 的颜色通道是GBR,不是一般的RGB
plt.subplot(341),plt.imshow(origin),plt.title('Origin')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.subplot(342),plt.imshow(gray, cmap='gray'),plt.title('Gray')

_, threshold1 = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)
plt.subplot(343),plt.imshow(threshold1, cmap='gray'),plt.title('Binary')

_, threshold2 = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV)
plt.subplot(344),plt.imshow(threshold2, cmap='gray'),plt.title('Binary Inverse')

_, threshold3 = cv2.threshold(gray, threshold, 255, cv2.THRESH_TRUNC)
plt.subplot(345),plt.imshow(threshold3, cmap='gray'),plt.title('Trunc')

_,threshold4 = cv2.threshold(gray, threshold, 255, cv2.THRESH_TOZERO)
plt.subplot(346),plt.imshow(threshold4, cmap='gray'),plt.title('To Zero')

_,threshold5 = cv2.threshold(gray, threshold, 255, cv2.THRESH_TOZERO_INV)
plt.subplot(347),plt.imshow(threshold5, cmap='gray'),plt.title('To Zero Inverse')

_,threshold6 = cv2.threshold(gray, threshold, 255, cv2.THRESH_TRIANGLE)
plt.subplot(348),plt.imshow(threshold6, cmap='gray'),plt.title('Triangle')

_,threshold9 = cv2.threshold(gray, threshold, 255, cv2.THRESH_OTSU) #otsu algorithm
plt.subplot(3,4,9),plt.imshow(threshold9, cmap='gray'),plt.title('Otsu')

_,threshold10 = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU) #otsu algorithm
plt.subplot(3,4,10),plt.imshow(threshold10, cmap='gray'),plt.title('THRESH_BINARY_INV | Otsu')

plt.suptitle('Threshold samples')
plt.show()

测试结果: