个性化阅读
专注于IT技术分析

Python使用OpenCV的阈值技术Set-1(简单阈值)

点击下载

阀值是OpenCV中的一项技术, 它是相对于提供的阈值的像素值分配。在阈值化中, 将每个像素值与阈值进行比较。如果像素值小于阈值, 则将其设置为0, 否则, 将其设置为最大值(通常为255)。阈值化是一种非常流行的分割技术, 用于将被视为前景的对象与背景分离。阈值是在其任一侧具有两个区域的值, 即低于阈值或高于阈值。

在计算机视觉中, 这种阈值处理技术是在灰度图像上完成的。因此, 最初, 必须在灰度颜色空间中转换图像。

If f (x, y)> T 
   then f (x, y) = 0 
else 
   f (x, y) = 255

where 
f (x, y) = Coordinate Pixel Value
T = Threshold Value.

在带有Python的OpenCV中, 该函数cv2.threshold用于阈值化。

语法:cv2.threshold(source, thresholdValue, maxVal, thresholdingTechnique)
参数:
-> source:输入图像数组(必须为灰度)。
-> thresholdValue:低于和高于此阈值的阈值, 像素值将相应更改。
-> maxVal:可以分配给像素的最大值。
-> thresholdingTechnique:要应用的阈值类型。

简单阈值

基本阈值技术是二进制阈值。对于每个像素, 应用相同的阈值。如果像素值小于阈值, 则将其设置为0, 否则, 将其设置为最大值。

不同的简单阈值处理技术是:

  • cv2.THRESH_BINARY:如果像素强度大于设置的阈值, 则将值设置为255, 否则设置为0(黑色)。
  • cv2.THRESH_BINARY_INV:的倒置或相反情况cv2.THRESH_BINARY.
  • cv.THRESH_TRUNC:如果像素强度值大于阈值, 则将其截断为阈值。像素值设置为与阈值相同。所有其他值保持不变。
  • cv.THRESH_TOZERO:对于所有像素强度, 像素强度均设置为0, 小于阈值。
  • 简历THRESH_TOZERO_INV:的倒置或相反情况cv2.THRESH_TOZERO.
Python使用OpenCV的阈值技术Set-1(简单阈值)1

以下是解释不同简单阈值处理技术的Python代码–

# Python programe to illustrate 
# simple 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
# all pixels value above 120 will 
# be set to 255
ret, thresh1 = cv2.threshold(img, 120 , 255 , cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img, 120 , 255 , cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img, 120 , 255 , cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img, 120 , 255 , cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img, 120 , 255 , cv2.THRESH_TOZERO_INV)
  
# the window showing output images
# with the corresponding thresholding 
# techniques applied to the input images
cv2.imshow( 'Binary Threshold' , thresh1)
cv2.imshow( 'Binary Threshold Inverted' , thresh2)
cv2.imshow( 'Truncated Threshold' , thresh3)
cv2.imshow( 'Set to 0' , thresh4)
cv2.imshow( 'Set to 0 Inverted' , thresh5)
    
# De-allocate any associated memory usage  
if cv2.waitKey( 0 ) & 0xff = = 27 : 
     cv2.destroyAllWindows()

输入如下:

Python使用OpenCV的阈值技术Set-1(简单阈值)2

输出如下:

Python使用OpenCV的阈值技术Set-1(简单阈值)3

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python使用OpenCV的阈值技术Set-1(简单阈值)

评论 抢沙发

评论前必须登录!