python-OpenCV之阈值处理

OpenCV函数原型:

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

返回值解释

returned_thresh_value 返回的阈值
dst 处理后的图片

参数解释

src 输入的图片,只能输入单通道图像,通常来说是灰度图
thresh 阈值
maxval 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
type

二值化操作的类型,包含以下5种类型:

  cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0

  cv2.THRESH_BINARY_INV THRESH_BINARY的反转

  cv2.THRESH_TRUNC 大于阈值部分设为阈值,否则不变

  cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0

  cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转

代码示例

import cv2 as cv
import numpy as np

# 读入图片
src = cv.imread('test2.jpg', flags=0)
# 设置文本
text = "Original Image"
# 将原图片复制一份,以在其上显示文字
ori = src.copy()
# 调用putText()函数在原图片上显示文字
cv.putText(ori, text, (400, 1800), cv.FONT_HERSHEY_COMPLEX, 5.0, (255, 0, 0), 12)

# 设置阈值
ThreshValue = 165
# 设置最大像素值
MaxVal = 230

# cv.THRESH_BINARY
returned_thresh_value, dst = cv.threshold(src, ThreshValue, MaxVal, cv.THRESH_BINARY)
cv.putText(dst, "cv.THRESH_BINARY", (400, 1800), cv.FONT_HERSHEY_COMPLEX, 4.0, (255, 0, 0), 12)
# cv.THRESH_BINARY_INV
returned_thresh_value1, dst1 = cv.threshold(src, ThreshValue, MaxVal, cv.THRESH_BINARY_INV)
cv.putText(dst1, "cv.THRESH_BINARY_INV", (400, 1800), cv.FONT_HERSHEY_COMPLEX, 4.0, (255, 0, 0), 12)
# cv.THRESH_TRUNC
returned_thresh_value2, dst2 = cv.threshold(src, ThreshValue, MaxVal, cv.THRESH_TRUNC)
cv.putText(dst2, "cv.THRESH_TRUNC", (400, 1800), cv.FONT_HERSHEY_COMPLEX, 4.0, (255, 0, 0), 12)
# cv.THRESH_TOZERO
returned_thresh_value3, dst3 = cv.threshold(src, ThreshValue, MaxVal, cv.THRESH_TOZERO)
cv.putText(dst3, "cv.THRESH_TOZERO", (400, 1800), cv.FONT_HERSHEY_COMPLEX, 4.0, (255, 0, 0), 12)
# cv.THRESH_TOZERO_INV
returned_thresh_value4, dst4 = cv.threshold(src, ThreshValue, MaxVal, cv.THRESH_TOZERO_INV)
cv.putText(dst4, "cv.THRESH_TOZERO_INV", (400, 1800), cv.FONT_HERSHEY_COMPLEX, 4.0, (255, 0, 0), 12)

cv.namedWindow('Thresh', cv.WINDOW_NORMAL)

# 将图片拼接起来
show0 = np.hstack([ori, dst, dst1])
show1 = np.hstack([dst2, dst3, dst4])
show = np.vstack([show0, show1])

# 显示图片
cv.imshow('Thresh', show)

cv.waitKey()
cv.destroyAllWindows()

处理效果

python-OpenCV之阈值处理_第1张图片

 

你可能感兴趣的:(python-OpenCV之阈值处理)