使用 skimage 的二值图像

Binary Image using skimage

我创建了一个将图像转换为灰度图像以及图像的二值图像的函数。但是,returned 值(应该是二值图像)显示为紫色和黄色。当我执行 'cmap = 'gray'' 时,它在函数中是正确的,但是,我不能在 return 上执行此操作。我怎样才能让它正确?

我当前的代码是:

def greyscale_and_binary(file, file_name):
    '''
    this function graphs a histogram for the greyscale for the file inputed. It converts the image to grayscale image
    It also creates a binary image for the file

    Parameters
    ----------
    file : Array of float32
        the image.
    file_name : str
        name of the file to be ouputted on the graph.

    Returns
    -------
    binary_file : array of bool
        binary of the file/image.

    '''
    gray_file = rgb2grey(file) #convert to grayscale
    threshold = skimage.filters.threshold_otsu(gray_file) #input value
    binary_file = (gray_file < threshold) #binary is when less than trheshold
    
    #plot histogram on grayscale image
    histogram, bin_edges = np.histogram(gray_file, bins = 256, range=(0,1))
    plt.title('Histogram of gray scale values:'+ file_name)
    plt.axvline(threshold, color = 'r', label = 'threshold') #threshold marked with a red vertical line
    plt.legend()
    plt.plot(bin_edges[0:-1], histogram)

    #plot binary, original image and gray scale image next to each other 
    fig, axes = plt.subplots(ncols=3, figsize=(8,3))
    ax = axes.ravel()

    ax[0].imshow(file)
    ax[0].set_title('original')

    ax[1].imshow(gray_file, cmap = 'gray')
    ax[1].set_title('grayscale')

    ax[2].imshow(binary_file, cmap = 'gray')
    ax[2].set_title('binary')
    
    #remove axis
    for a in ax:
        a.axis('off')

    fig.tight_layout()
    plt.show()
    return binary_file


binarys = greyscale_and_binary(image, 'image')



binarys = morph.remove_small_objects(binarys)
img_blob = morph.remove_small_holes(binarys)

此外,我的最后两个功能不起作用。它不会去除小物体或小孔。任何原因或如何解决它?

我的二进制图(旋转)与我想要的输出

这确实是一个颜色映射问题。您可以在代码的最开始使用 matplotlib rcparams 为所有图设置全局颜色图:

import matplotlib as mpl
mpl.rc('image', cmap='gray')

这将告诉 matplotlib 在整个运行时使用此设置。您可以在运行时更改这些,还可以设置许多其他参数,如 documentation.

中所述