基于阈值方法分割彩色图像

作者: 陨星落云 | 来源:发表于2020-02-17 12:25 被阅读0次

    图像阈值分割

    1.查看图像直方图

    2.选择合适的阈值

    3.利用形态学操作,填补局部空洞

    4.掩膜,得到图像结果

    查看图像直方图,确定阈值
    from skimage import io,img_as_ubyte
    import numpy as np
    import matplotlib.pyplot as plt
    
    img = img_as_ubyte(io.imread('macro-photography-of-strawberry-934066.jpg',as_gray=True))
    # print(img)
    
    plt.figure(figsize=(10,8),dpi=80)
    plt.subplot(221)
    plt.imshow(img,cmap="gray")
    plt.xlabel("原图",fontproperties='SimHei')
    plt.subplot(222)
    # 直方图显示
    plt.hist(img.flat,bins=100,range=(0,225))
    plt.xlabel("直方图",fontproperties='SimHei')
    segm1 = (img<=180)
    segm2 = (img>180)
    plt.subplot(223)
    plt.imshow(segm1,cmap="gray")
    plt.xlabel("前景",fontproperties='SimHei')
    plt.subplot(224)
    plt.imshow(segm2,cmap="gray")
    plt.xlabel("背景",fontproperties='SimHei')
    plt.show()
    

    输出结果:

    查看直方图,设置阈值
    阈值分割彩色图像
    from skimage import io,img_as_ubyte
    from skimage.color import rgb2gray
    from skimage.morphology import opening,disk
    import numpy as np
    import matplotlib.pyplot as plt
    
    # 读取彩色图像,并将图像类型设置为8位(0-255)
    img = img_as_ubyte(io.imread('macro-photography-of-strawberry-934066.jpg'))
    # 转换成灰度图像(类型自动转为0~1或-1~1),并将图像类型设置为8位
    img_gray = img_as_ubyte(rgb2gray(img))
    
    # 读取灰度图像的高h和宽w
    h,w = img_gray.shape
    # print(img_gray)
    
    # 设置阈值
    segm1 = (img_gray>180)
    # print(segm1)
    
    # 开运算
    kernel = disk(10)   
    img_opening = opening(segm1,kernel)
    # 将单通道阈值,转为RGB通道的阈值
    segm = np.tile(img_opening.reshape(h,w,1),3)
    
    # 复制一份彩色图像
    img1 = img.copy()
    # 掩膜操作
    img1[segm] = 0
    
    # 显示图像
    plt.figure(figsize=(10,8),dpi=80)
    plt.subplot(121)
    plt.imshow(img)
    plt.xlabel("原图像",fontproperties='SimHei')
    plt.subplot(122)
    plt.imshow(img1)
    plt.xlabel("阈值分割结果",fontproperties='SimHei')
    plt.show()
    

    输出结果:

    阈值分割彩色图像.png

    相关文章

      网友评论

        本文标题:基于阈值方法分割彩色图像

        本文链接:https://www.haomeiwen.com/subject/ildbfhtx.html