赞
踩
- # -*- coding=GBK -*-
- import cv2 as cv
-
-
- # 固定阈值
- def threshold_image(image):
- gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
- cv.imshow("before", gray)
-
- ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) # 大律法,全局自适应阈值 参数0可改为任意数字但不起作用
- print("Threshold:%s" % ret)
- cv.imshow("OTSU", binary)
-
- ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE) # TRIANGLE法,,全局自适应阈值, 参数0可改为任意数字但不起作用,适用于单个波峰
- print("Threshold:%s" % ret)
- cv.imshow("TRIANGLE", binary)
-
- ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY) # 自定义阈值为150,大于150的是白色 小于的是黑色
- print("Threshold:%s" % ret)
- cv.imshow("customize", binary)
-
- ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV) # 自定义阈值为150,大于150的是黑色 小于的是白色
- print("Threshold:%s" % ret)
- cv.imshow("customize_ReverseColor", binary)
-
- ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TRUNC) # 截断 大于150的是改为150 小于150的保留
- print("Threshold:%s" % ret)
- cv.imshow("cutdown_1", binary)
-
- ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TOZERO) # 截断 小于150的是改为150 大于150的保留
- print("Threshold:%s" % ret)
- cv.imshow("cutdown_2", binary)
-
-
- src = cv.imread("fengling.jpg")
- threshold_image(src)
- cv.waitKey(0)
- cv.destroyAllWindows()
threshold()函数参考:https://blog.csdn.net/sinat_21258931/article/details/61418681
- # -*- coding=GBK -*-
- import cv2 as cv
-
-
- #自适应阈值
- def local_image(image):
- gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
- cv.imshow("before", gray)
- binary1 = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 25, 10) # 均值
- cv.imshow("Partial_1", binary1)
- binary2 = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10) # 高斯处理
- cv.imshow("Partial_2", binary2)
-
-
- src = cv.imread("fengling.jpg")
- local_image(src)
- cv.waitKey(0)
- cv.destroyAllWindows()
adaptiveThreshold()函数:https://blog.csdn.net/laoyezha/article/details/106445437
像素平均阈值二值化
代码:
- # -*- coding=GBK -*-
- import cv2 as cv
- import numpy as np
-
-
- # 求出图像均值作为阈值来二值化
- def custom_image(image):
- gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
- cv.imshow("before", gray)
- 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("Binary", binary)
-
-
- src = cv.imread("fengling.jpg")
- custom_image(src)
- cv.waitKey(0)
- cv.destroyAllWindows()
结果:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。