zoukankan      html  css  js  c++  java
  • 图像阈值

    理论

    图像阈值分割 利用图像中 要提取的目标区域 与 其背景 在 灰度特性 上的差异,把图像看作 具有不同灰度级的两类区域 (目标区域和背景区域)的组合。

    选取一个比较合理的阈值,以确定图像中每个像素点 应该属于目标区域 还是背景区域,从而产生相应的二值图像。

    阈值分割法的特点是:适用于 目标与背景灰度 有较强对比 的情况,重要的是背景或物体的 灰度比较单一,而且总可以得到封闭连通区域 的边界。


    threshold 方法

    threshold(src, thresh, maxval, type[, dst]) -> retval, dst

    src:原始图像;
    thresh:阈值,在 0--255 之间;如 127;
    maxval:最大可能值,最大为 255;
    type:二值化操作类型;方法类型,怎么样判断阈值,判断后怎么处理

    • cv2.THRESH_TOZERO_INV
    • cv2.THRESH_BINARY 超过阈值部分取 maxval (最大值), 否则取0
    • cv2.THRESH_BINARY_INV, THRESH_BINARY的反转
    • cV2.THRESH_TRUNC, 大于阈值部分设为阈值,否则不变;如阈值设置为 127,大于 127的,设置为 127
    • cv2.THRESH_TOZERO, 大于阈值部分不改变,否则设为0
    • cv2.THRESH_TOZERO_INV,THRESH_TOZERO的反转

    INV 这个代表反转(inverse),在很多地方都会用到


    下图做了一个形象的总结:


    调用示例

    import cv2
    import matplotlib.pyplot as plt
    
    # 读取为灰度图
    img_gray=cv2.imread('dj.jpg',cv2.IMREAD_GRAYSCALE)
    
    ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
    ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
    ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
    ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
    ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
    
    titles = [' Original ' , 'BINARY', 'BINARY_INV', ' TRUNC', 'TOZERO', 'TOZERO_INV']
    images = [img_gray, thresh1, thresh2, thresh3, thresh4, thresh5]
    
    for i in range(6) :
        plt.subplot(2, 3, i + 1),
        plt.imshow(images[i], 'gray' )
        plt.title(titles[i])
        plt.xticks([]), plt.yticks([])
        
    plt.show()
    

    ## 彩色图像的遍历
     
    img = cv2.imread('lena.jpg')
    h,w,n = img.shape
    img2 = img.copy()
     
    for i in range(h):
        for j in range(w):
            img2[i,j][1] = 0   
          
    cv_show(img2)
    
  • 相关阅读:
    我真的没读野鸡大学!是他们不好好起名字!
    Request.Cookies和Response.Cookies
    深受理科生喜欢的10大专业
    如何玩转“互联网+教育”?
    js调试工具Console命令详解
    XSS获取cookie并利用
    257. Binary Tree Paths
    EXEC sp_executesql with multiple parameters
    235. Lowest Common Ancestor of a Binary Search Tree
    226. Invert Binary Tree
  • 原文地址:https://www.cnblogs.com/fldev/p/14371294.html
Copyright © 2011-2022 走看看