0

I am using these libraries:

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

My code is as follows:

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')

I am trying to save the image using the following line of code:

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

However this shows me the error:

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

I need an image in .bmp format, because I need it quantized at 8 bits. How can I solve this problem? Or there is another way to save an imagen in .bmp format?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 1
    Both BMP and PNG can save to 8 bits with a palette, but they can save 24 bits too so it won't happen automatically. You need to apply a palette as a separate step. – Mark Ransom Jul 31 '21 at 00:02

2 Answers2

2

Seems like Matplotlib does not support saving in BMP format. You'll have to convert the figure into a Pillow image first, and then save that. To do this, you can use PIL.Image.frombytes() as suggested in this other answer.

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')
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
1

If bmp is not supported as a save format. Then I guess there is no other way that let you save it as bmp with plt directly. If so, what we can do is to save it as .PNG first and then convert it to bmp. We can use PIL to do this. And you have PIL in your code so.

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")
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
Zichzheng
  • 1,090
  • 7
  • 25