cv2.threshold阈值相关用法说明

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

src:输入图,只能输入单通道图像,通常来说为灰度图
dst:输出图
thresh:阈值
maxval:当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
type:二值化操作的类型,就是怎么处理阈值,包含以下5种类型:cv2.THRESH_BINARY;cv2.THRESH_BINARY_INV;cv2.THRESH_TRUNC;cv2.THRESH_TOZERO;cv2.THRESH_TOZERO_INV;

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

cv2.THRESH_BINARY_INV THRESH_BINARY的反转

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

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

cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转

cv2.THRESH_OTSU   方法能够根据当前图像生成最佳的类间分割阈值,原理是遍历所有可能的阈值,从而找到最合适的阈值,thresh:阈值要设置为0,适合双峰型阀值,其他情况不适用

import cv2
import matplotlib.pyplot as plt
img = cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('img_gray)', img_gray)
ret1, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret2, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret3, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret4, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret5, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)

 

posted @ 2023-08-26 15:33  hotzhml  阅读(179)  评论(0编辑  收藏  举报