当前位置:   article > 正文

python实现opencv学习十三:图像二值化

python实现opencv学习十三:图像二值化

固定阈值二值化

代码:

  1. # -*- coding=GBK -*-
  2. import cv2 as cv
  3. # 固定阈值
  4. def threshold_image(image):
  5. gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
  6. cv.imshow("before", gray)
  7. ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU) # 大律法,全局自适应阈值 参数0可改为任意数字但不起作用
  8. print("Threshold:%s" % ret)
  9. cv.imshow("OTSU", binary)
  10. ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE) # TRIANGLE法,,全局自适应阈值, 参数0可改为任意数字但不起作用,适用于单个波峰
  11. print("Threshold:%s" % ret)
  12. cv.imshow("TRIANGLE", binary)
  13. ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY) # 自定义阈值为150,大于150的是白色 小于的是黑色
  14. print("Threshold:%s" % ret)
  15. cv.imshow("customize", binary)
  16. ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_BINARY_INV) # 自定义阈值为150,大于150的是黑色 小于的是白色
  17. print("Threshold:%s" % ret)
  18. cv.imshow("customize_ReverseColor", binary)
  19. ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TRUNC) # 截断 大于150的是改为150 小于150的保留
  20. print("Threshold:%s" % ret)
  21. cv.imshow("cutdown_1", binary)
  22. ret, binary = cv.threshold(gray, 150, 255, cv.THRESH_TOZERO) # 截断 小于150的是改为150 大于150的保留
  23. print("Threshold:%s" % ret)
  24. cv.imshow("cutdown_2", binary)
  25. src = cv.imread("fengling.jpg")
  26. threshold_image(src)
  27. cv.waitKey(0)
  28. cv.destroyAllWindows()

结果:

备注:

threshold()函数参考:https://blog.csdn.net/sinat_21258931/article/details/61418681


自适应阈值二值化

代码:

  1. # -*- coding=GBK -*-
  2. import cv2 as cv
  3. #自适应阈值
  4. def local_image(image):
  5. gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
  6. cv.imshow("before", gray)
  7. binary1 = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 25, 10) # 均值
  8. cv.imshow("Partial_1", binary1)
  9. binary2 = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 25, 10) # 高斯处理
  10. cv.imshow("Partial_2", binary2)
  11. src = cv.imread("fengling.jpg")
  12. local_image(src)
  13. cv.waitKey(0)
  14. cv.destroyAllWindows()

结果:

备注:

adaptiveThreshold()函数:https://blog.csdn.net/laoyezha/article/details/106445437


像素平均阈值二值化

代码:

  1. # -*- coding=GBK -*-
  2. import cv2 as cv
  3. import numpy as np
  4. # 求出图像均值作为阈值来二值化
  5. def custom_image(image):
  6. gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
  7. cv.imshow("before", gray)
  8. h, w = gray.shape[:2]
  9. m = np.reshape(gray, [1, w * h]) # 化为一维数组
  10. mean = m.sum() / (w * h)
  11. print("mean: ", mean)
  12. ret, binary = cv.threshold(gray, mean, 255, cv.THRESH_BINARY)
  13. cv.imshow("Binary", binary)
  14. src = cv.imread("fengling.jpg")
  15. custom_image(src)
  16. cv.waitKey(0)
  17. cv.destroyAllWindows()

结果:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小惠珠哦/article/detail/954991
推荐阅读
相关标签
  

闽ICP备14008679号