0

I am using BytIO to first convert the plot (matplotlib) to PNG format and then obtaining the array of the PNG image, here is the code:

from matplotlib import pyplot as plt
import numpy as np
import io
from PIL import Image

fig, ax = plt.subplots()
ax.text(0.0,0.0,"Test", fontsize=45)
ax.axis('off')
ax.imshow(np.random.random((3,3)))

with io.BytesIO() as memf:
    fig.savefig(memf, format='PNG')
    memf.seek(0)
    img = Image.open(memf).convert('RGB')
    arr = np.asarray(img)
    img.show()
plt.show()
print(arr)

The image looks fine, but the array is not, it shows all values to be 255 in all 3 dimensions (RGB). What am I doing wrong?

This is the image (img):

enter image description here

goodvibration
  • 5,980
  • 4
  • 28
  • 61

2 Answers2

2

arr contains other values besides 255. (Evaluate np.where(arr != 255) to see where.) The reason why you are seeing so many 255's is because the image contains a white border. To remove the white border, see Joe Kington's or matehat's method. For example, using Joe Kington's method (controlling the extent):

from PIL import Image
import io
from matplotlib import pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ax.axis('off')
ax.text(0.0,0.0,"Test", fontsize=45)
ax.imshow(np.random.random((3,3)))

with io.BytesIO() as memf:
    extent = ax.get_window_extent()
    extent = extent.transformed(fig.dpi_scale_trans.inverted())
    fig.savefig(memf, format='PNG', bbox_inches=extent)
    memf.seek(0)
    img = Image.open(memf).convert('RGB')
    arr = np.asarray(img)
    img.save('/tmp/out.png')

enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

Extending arr = np.asarray(img) to:

arr = []
for b in bytearray(np.asarray(img)):
    if b < 255:
        arr += [b]

Shows that not all values in this array are equal to 255.

goodvibration
  • 5,980
  • 4
  • 28
  • 61