📜  Python|使用 OpenCV 的阈值技术 | Set-2(自适应阈值)

📅  最后修改于: 2022-05-13 01:55:38.189000             🧑  作者: Mango

Python|使用 OpenCV 的阈值技术 | Set-2(自适应阈值)

先决条件:使用 OpenCV 进行简单阈值处理

在上一篇文章中,使用不同类型的阈值技术解释了简单阈值。另一种阈值技术是自适应阈值。在简单阈值处理中,使用了一个全局阈值值,该值始终保持不变。因此,在不同区域照明条件变化的情况下,恒定的阈值将无济于事。自适应阈值是针对较小区域计算阈值的方法。这导致不同区域相对于照明变化的不同阈值。我们为此使用cv2.adaptiveThreshold

以下是Python实现:

# Python program to illustrate 
# adaptive thresholding type on an image
       
# organizing imports 
import cv2 
import numpy as np 
   
# path to input image is specified and  
# image is loaded with imread command 
image1 = cv2.imread('input1.jpg') 
   
# cv2.cvtColor is applied over the
# image input with applied parameters
# to convert the image in grayscale 
img = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
   
# applying different thresholding 
# techniques on the input image
thresh1 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,
                                          cv2.THRESH_BINARY, 199, 5)
  
thresh2 = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                          cv2.THRESH_BINARY, 199, 5)
  
# the window showing output images
# with the corresponding thresholding 
# techniques applied to the input image
cv2.imshow('Adaptive Mean', thresh1)
cv2.imshow('Adaptive Gaussian', thresh2)
  
     
# De-allocate any associated memory usage  
if cv2.waitKey(0) & 0xff == 27: 
    cv2.destroyAllWindows() 

输入图像

输出