Search code examples
pythonscikit-image

Binary Image using skimage


I created a function that converts an image to grayscale image and also a binary image for the image. However, the returned value(which should be the binary image), is coming out purple and yellow. It comes out correct in the function when I do 'cmap = 'gray'', however, I can't do that on the return. How can I make it correct?

My current code is:

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)

Also, my last two functions aren't working. It doesn't remove the small objects or the small holes. Any reason why or how to fix it?

My plot for binarys(rotated) versus my desired outputmy desired output enter image description here


Solution

  • This is indeed a colormap issue. You can set the global colormap for all plots using the matplotlib rcparams at the very start of your code:

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

    This will tell matplotlib to use this setting for the entire runtime. You can change these during runtime and there are also a bunch of other params you can set, described in the documentation.