【问题标题】:Not able to use colormap and save an image afterwards without displacement无法使用颜色图并在没有位移的情况下保存图像
【发布时间】:2019-01-13 20:02:56
【问题描述】:

我正在尝试在图片上使用 matplotlib 中的几个颜色图,然后将其保存。我尝试了很多东西,但我无法保存它而不使图像在顶部移动 1 或 2 个像素。我也觉得图片的比例有些小错误。 图片大小为 64x64 像素。

我尝试使用 dpi,并将 dpi 设置为 96(我的屏幕 dpi)、100 和 80。这些都不起作用。 我通过尝试获得 64x64 像素输出得到了 0.84。

cmappsL1 = ["Paired", "Paired_r", "Spectral", "Spectral_r", "flag", "flag_r", "tab10"]
image = "example.png"
imgpath = "C:\\Users\\"

for i in range(len(cmapps)):
    fig = plt.figure(figsize=(0.84, 0.84)) #needed to get rid of padding
    ax = fig.add_subplot(1, 1, 1) #needed to get rid of pyplot padding
    plt.imshow(image, cmap=str(cmapps[i])) #use colormap
    plt.xticks([])#get rid of scale
    plt.yticks([])#get rid of scale
    ax.axes.get_xaxis().set_visible(False)#get rid of axis
    ax.axes.get_yaxis().set_visible(False)#get rid of axis
    ax.set_frame_on(False)#get rid of frame
    plt.savefig(imgpath+cmapps[i]+'.png', bbox_inches = 'tight', pad_inches = 0)
    plt.close(fig)

生成的图片比原始图片稍微高一点,而且有点不安。如何保存带有颜色图的图片,使其具有与原始属性完全相同的属性,除了颜色图的使用?

【问题讨论】:

    标签: python-3.x matplotlib save colormap


    【解决方案1】:

    好像根本不需要创建图,直接用imsave就可以了

    cmappsL1 = ["Paired", "Paired_r", "Spectral", "Spectral_r", "flag", "flag_r", "tab10"]
    image = plt.imread("example.png")
    
    for i in range(len(cmapps)):
        plt.imsave(cmapps[i]+'.png', image, cmap=str(cmapps[i])) #use colormap
    

    如果您真的想创建一个没有边距和填充的图形,请参阅Can't remove matplotlib's padding around imshow() figurethis answer。关键是不要使用bbox_inches = 'tight' 并创建一个正方形,例如figsize*dpi == pixel dimensions

    【讨论】:

    • 谢谢,这是第二个帖子,帮助了我。
    • 请问,如果唯一的目的是再次保存它,您为什么还要创建该图?或者换句话说,为什么单独imsave 不够?
    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 2011-04-07
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 1970-01-01
    相关资源
    最近更新 更多