matplotlib顯示帶colorbar的熱圖並保存

需求

在熱圖邊畫出colorbar,並設置一些參數使得colorbar美觀。

然後保存圖像。

代碼:

def save_jet_figure(image, filename):
    ''' save jet colormap figure using matplotlib
    
    Args: 
    ---

        image: ndarray of (width, height)
            input image in gray scale.

        filename: str
            save filename

    Returns:
    ---

        None

    Example:
    --- 

        from skimage.io import imread
        import matplotlib.pyplot as plt
        from mpl_toolkits.axes_grid1 import make_axes_locatable

        img = imread('./test.png')
        img = img[:, :, 0]
        save_jet_figure(img, './result.png') 

        plt.show()
        
    '''
    # show image
    fig = plt.figure(tight_layout=True)
    ax = fig.add_subplot(111)
    im = ax.imshow(image, 'jet')
    ax.axis('off')

    # colorbar
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='2%', pad=0.04)
    cbar = plt.colorbar(im, 
                        cax=cax, 
                        extend='both', 
                        extendrect=True, 
                        ticks=[0.0, 0.5, 1.0],
                        )
    cbar.outline.set_visible(False)
    cbar.ax.tick_params(labelsize=8, 
                        width=0,
                        length=0,
                        pad=1,)

    # save image
    fig.savefig(filename, 
                bbox_inches='tight',
                pad_inches=0,
                transparent=True,
                dpi=300)

結果:結果

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章