python+openCV图像处理(十六)二值化阈值
作者:互联网
import cv2 as cv
import numpy as np
def threshold_demo(image):
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY|cv.THRESH_OTSU)
print("threshold value %s"%ret)
cv.imshow("threshold_binary", binary)
def local_threshold(image):#自适应阈值二值化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
binary = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10)
cv.imshow("local_threshold_binary", binary)
def custom_threshold(image):#自定义二值化
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
h, w = gray.shape[:2]
m = np.reshape(gray, [1, w*h])
mean = m.sum() / (w*h)
print("mean : ", mean)
ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
cv.imshow("custom_threshold_binary", binary)
src = cv.imread("D:/vcprojects/images/case2.png")
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
cv.imshow("input image", src)
threshold_demo(src)
local_threshold(src)
custom_threshold(src)
cv.waitKey(0)
cv.destroyAllWindows()
标签:binary,gray,python,image,cv,openCV,THRESH,threshold,二值化 来源: https://blog.csdn.net/yang_jianfeng/article/details/111828710