【问题标题】:Saving a matplotlib figure in BMP format以 BMP 格式保存 matplotlib 图
【发布时间】:2021-10-06 09:54:00
【问题描述】:

我正在使用这些库:

import matplotlib.pyplot as plt
from PIL import Image as im

我的代码如下:

fig = plt.figure(dpi=250) # 
ax1 = fig.add_subplot(2, 1, 1)
pos1 =ax1.imshow(amplitud_DCO08,cmap='gray')
ax1.title.set_text('Amplitud del DCO')
fig.savefig('AmplitudDCO_escalado08',dpi=250, format='bmp')

我正在尝试使用以下代码行保存图像:

fig.savefig('AmplitudDCO_escalado08',dpi=250, format='bmp')

但是这向我显示了错误:

Format 'bmp' is not supported(supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff).

我需要.bmp 格式的图像,因为我需要将其量化为 8 位。我怎么解决这个问题?或者还有其他方法可以将图片保存为.bmp 格式?

【问题讨论】:

  • BMP 和 PNG 都可以使用调色板保存到 8 位,但它们也可以保存 24 位,因此不会自动发生。您需要将调色板作为单独的步骤应用。

标签: python


【解决方案1】:

如果不支持 bmp 作为保存格式。那么我想没有其他方法可以让您直接将其保存为 bmp 与 plt 。如果是这样,我们可以做的是先将其保存为.PNG,然后将其转换为bmp。我们可以使用PIL 来做到这一点。而且你的代码中有 PIL。

fig = plt.figure(dpi=250) # 
ax1 = fig.add_subplot(2, 1, 1)
pos1 =ax1.imshow(amplitud_DCO08,cmap='gray')
ax1.title.set_text('Amplitud del DCO')
fig.savefig('AmplitudDCO_escalado08,PNG',dpi=250))
im.open("AmplitudDCO_escalado08.PNG").save("AmplitudDCO_escalado08.bmp")

【讨论】:

    【解决方案2】:

    好像 Matplotlib 不支持以 BMP 格式保存。您必须先将图形转换为 Pillow 图像,然后保存。为此,您可以按照this other answer 中的建议使用PIL.Image.frombytes()。

    import matplotlib.pyplot as plt
    from PIL import Image as im
    
    fig = plt.figure(dpi=250) # 
    ax1 = fig.add_subplot(2, 1, 1)
    pos1 =ax1.imshow(amplitud_DCO08,cmap='gray')
    ax1.title.set_text('Amplitud del DCO')
    
    image = im.frombytes('RGB', fig.canvas.get_width_height(), fig.canvas.tostring_rgb())
    image.save('AmplitudDCO_escalado08.bmp')
    

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-16
      • 2023-03-09
      • 2014-10-16
      • 2015-12-21
      • 1970-01-01
      相关资源
      最近更新 更多