zoukankan      html  css  js  c++  java
  • OpenCV-Python入门教程5-阈值分割

    一、固定阈值分割

    import cv2
    import matplotlib.pyplot as plt
    # 灰度图读入
    img = cv2.imread('gradient.jpg', 0)
    
    # 阈值分割
    ret, th = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    
    cv2.imshow('thresh', th)
    cv2.waitKey(0)

    cv2.threshold()用来实现阈值分割,有4个参数:

    • 参数1:要处理的原图,一般是灰度图
    • 参数2:设定的阈值
    • 参数3:最大阈值,一般是255
    • 参数4:阈值的方式,主要有5种,详情:ThresholdTypes

    理解这5种阈值方式:

    # 应用5种不同的阈值方法
    ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    ret, th2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
    ret, th3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
    ret, th4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)
    ret, th5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)
    titles = ['Original', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
    images = [img, th1, th2, th3, th4, th5]
    
    # 使用Matplotlib显示
    # 两行三列图
    for i in range(6):
        plt.subplot(2, 3, i + 1)
        plt.imshow(images[i], 'gray')
        plt.title(titles[i], fontsize=8)
        plt.xticks([]), plt.yticks([])  # 隐藏坐标轴
    plt.show()

    固定阈值将整幅图片分成两类值,它并不适用于明暗分布不均的图片。而cv2.adaptiveThreshold()自适应阈值会每次取图片的一小部分计算阈值。这样图片不同区域的阈值就不尽相同。

    二、自适应矩阵

    # 自适应阈值对比固定阈值
    img = cv2.imread('sudoku.jpg', 0)
    
    # 固定阈值
    ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    
    # 自适应阈值
    th2 = cv2.adaptiveThreshold(
        img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 4)
    th3 = cv2.adaptiveThreshold(
        img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 17, 6)
    
    titles = ['Original', 'Global(v = 127)', 'Adaptive Mean', 'Adaptve Gaussian']
    images = [img, th1, th2, th3]
    
    for i in range(4):
        plt.subplot(2, 2, i + 1), plt.imshow(images[i], 'gray')
        plt.title(titles[i], fontsize=8)
        plt.xticks([]), plt.yticks([])  # 隐藏坐标轴
    plt.show()

    cv2.adaptiveThreshold()的6个参数:

    • 参数1:要处理的原图
    • 参数2:最大阈值,一般为255
    • 参数3:小区域阈值的计算方式

        ADAPTIVE_THRESH_MEAN_C:小区域内取均值

        ADAPTIVE_THRESH_GAUSSIAN_C:小区域内加权求和,权重是高斯核

    • 参数4:阈值方式(上面提到的那5种)
    • 参数5:小区域的面积,如11就是11 * 11的小块
    • 参数6:最终阈值等于小区域计算出的阈值再减去此值

    我们前面固定阈值的时候使用了127,那怎么知道这个阈值好不好呢?这个需要不断的尝试,在很多文献中在特定的场景下有经验阈值。Otsu阈值法就提供了一种自动高效的二值化方法。我将在下一篇提到。

    三、小结

    cv2.threshold()用来进行固定阈值分割,固定阈值分割不适用于光线不均匀的图片,所以用cv2.adaptiveThreshold()进行自适应阈值分割。当然,对于不同图片可以采用的不同的阈值分割方法。

     

  • 相关阅读:
    SPOJ 694 (后缀数组) Distinct Substrings
    POJ 2774 (后缀数组 最长公共字串) Long Long Message
    POJ 3693 (后缀数组) Maximum repetition substring
    POJ 3261 (后缀数组 二分) Milk Patterns
    UVa 1149 (贪心) Bin Packing
    UVa 12206 (字符串哈希) Stammering Aliens
    UVa 11210 (DFS) Chinese Mahjong
    UVa (BFS) The Monocycle
    UVa 11624 (BFS) Fire!
    HDU 3032 (Nim博弈变形) Nim or not Nim?
  • 原文地址:https://www.cnblogs.com/gezhuangzhuang/p/10292389.html
Copyright © 2011-2022 走看看