Opencv Python 简明教程

OpenCV Python - Image Threshold

在数字图像处理中,阈值处理是一个基于像素强度阈值创建二值图像的过程。阈值处理过程将前景像素与背景像素分离开来。

In digital image processing, the thresholding is a process of creating a binary image based on a threshold value of pixel intensity. Thresholding process separates the foreground pixels from background pixels.

OpenCV 提供了执行 simple, adaptiveOtsu’s 阈值处理的函数。

OpenCV provides functions to perform simple, adaptive and Otsu’s thresholding.

在简单阈值化中,所有值小于阈值的像素都被设置为零,其余的则被设置为最大像素值。这是最简单的阈值化形式。

In simple thresholding, all pixels with value less than threshold are set to zero, rest to the maximum pixel value. This is the simplest form of thresholding.

cv2.threshold() 函数具有以下定义。

The cv2.threshold() function has the following definition.

cv2.threshold((src, thresh, maxval, type, dst)

Parameters

图像阈值化的参数如下:

The parameters for the image thresholding are as follows −

  1. Src: Input array.

  2. Dst: Output array of same size.

  3. Thresh: Threshold value.

  4. Maxval: Maximum value.

  5. Type: Thresholding type.

Types of Thresholding

其他类型的阈值化如下所示:

Other types of thresholding are enumerated as below −

Sr.No

Type & Function

1

cv.THRESH_BINARY dst(x,y) = maxval if src(x,y)>thresh 0 otherwise

2

cv.THRESH_BINARY_INV dst(x,y)=0 if src(x,y)>thresh maxval otherwise

3

cv.THRESH_TRUNC dst(x,y)=threshold if src(x,y)>thresh src(x,y) otherwise

4

cv.THRESH_TOZERO dst(x,y)=src(x,y) if src(x,y)>thresh 0 otherwise

5

cv.THRESH_TOZERO_INV dst(x,y)=0 if src(x,y)>thresh src(x,y)otherwise

这些阈值类型根据以下图表对输入图像执行操作:

These threshold types result in operation on input image according to following diagram −

threshold

threshold() 函数返回所使用的阈值和阈值图像。

The threshold() function returns threshold used and threshold image.

以下程序通过将阈值设为 127,从原始图像生成一个从 255 到 0 具有灰色值渐变的二进制图像。

Following program produces a binary image from the original with a gradient of grey values from 255 to 0 by setting a threshold to 127.

Example

最初的和产生的阈值二进制图像使用 Matplotlib 库并排绘制。

Original and resultant threshold binary images are plotted side by side using Matplotlib library.

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('gradient.png',0)
ret,img1 = cv.threshold(img,127,255,cv.THRESH_BINARY)

plt.subplot(2,3,1),plt.imshow(img,'gray',vmin=0,vmax=255)
plt.title('Original')
plt.subplot(2,3,2),plt.imshow(img1,'gray',vmin=0,vmax=255)
plt.title('Binary')
plt.show()

Output

threshold binary

自适应阈值化根据其周围的一个小区域确定像素的阈值。因此,得到了同一图像中不同区域的不同阈值。这为照明不同的图像提供了更好的结果。

The adaptive thresholding determines the threshold for a pixel based on a small region around it. So, different thresholds for different regions of the same image are obtained. This gives better results for images with varying illumination.

cv2.adaptiveThreshold() 方法采用以下输入参数:

The cv2.adaptiveThreshold() method takes following input arguments −

cv.adaptiveThreshold( src, maxValue, adaptiveMethod, thresholdType, blockSize, C[, dst] )

adaptiveMethod 具有以下枚举值:

The adaptiveMethod has following enumerated values −

  1. cv.ADAPTIVE_THRESH_MEAN_C − The threshold value is the mean of the neighbourhood area minus the constant C.

  2. cv.ADAPTIVE_THRESH_GAUSSIAN_C − The threshold value is a Gaussianweighted sum of the neighbourhood values minus the constant C.

Example

在下面的示例中,原始图像 (messi.jpg) 应用平均值和高斯自适应阈值化。

In the example below, the original image (messi.jpg is applied with mean and Gaussian adaptive thresholding.

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('messi.jpg',0)
img = cv.medianBlur(img,5)
th1 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
   cv.THRESH_BINARY,11,2)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
   cv.THRESH_BINARY,11,2)
titles = ['Original', 'Mean Thresholding', 'Gaussian Thresholding']
images = [img, th1, th2]
for i in range(3):
   plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
   plt.title(titles[i])
   plt.xticks([]),plt.yticks([])
plt.show()

Output

原始图像和自适应阈值二值图像使用 matplotlib 绘制,如下所示 −

Original as well as adaptive threshold binary images are plotted by using matplotlib as shown below −

adaptive threshold binary

Example

OTSU 算法从图像直方图中自动确定阈值。我们需要在 THRESH-BINARY 标志中传递 cv.THRES_OTSU 标志。

OTSU algorithm determines the threshold value automatically from the image histogram. We need to pass the cv.THRES_OTSU flag in addition to the THRESH-BINARY flag.

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('messi.jpg',0)
# global thresholding
ret1,img1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
# Otsu's thresholding
ret2,img2 = cv.threshold(img,0,255,cv.THRESH_BINARY+cv.THRESH_OTSU)
plt.subplot(2,2,1),plt.imshow(img,'gray',vmin=0,vmax=255)
plt.title('Original')
plt.subplot(2,2,2),plt.imshow(img1,'gray')

plt.title('Binary')
plt.subplot(2,2,3),plt.imshow(img2,'gray')
plt.title('OTSU')
plt.show()

Output

matplotlib 的绘图结果如下所示 −

The matplotlib’s plot result is as follows −

image histogram