使用 OpenCV 对图像进行二值阈值处理


在该程序中,我们将使用 OpenCV 对图像执行二值阈值处理。

阈值处理是一个过程,其中每个像素的值根据阈值进行更改。如果像素小于阈值,则为其赋予某个值,如果像素大于阈值,则为其赋予另一个值。在二值阈值处理中,如果像素的值小于阈值,则为其赋予值 0,即黑色。如果大于阈值,则为其指定 255,即白色。

原始图像

算法

Step 1: Import cv2.
Step 2: Define threshold and max_val.
Step 3: Pass these parameters in the cv2.threshold value and specify the type of thresholding you want to do.
Step 4: Display the output.

示例代码

import cv2

image = cv2.imread('testimage.jpg')
threshold_value = 120
max_val = 255
ret, image = cv2.threshold(image, threshold_value, max_val, cv2.THRESH_BINARY)
cv2.imshow('BinaryThresholding', image)

输出

说明

程序中的 ret 变量仅返回阈值。对于大于阈值的值的任何像素,它们将被 max_val (即 255) 替换。

更新于: 17-Mar-2021

653 次浏览

激活您的事业

通过完成课程获得认证

开始
广告
© . All rights reserved.