Search code examples
pythonnumpypython-imaging-libraryrgbwebp

How to save a numpy array to a webp file?


import numpy as np
from PIL import Image

I have a numpy array res:

res = \
np.array([[[  1, 142,  68],
           [  1, 142,  74]],
   
          [[  1, 142,  70],
           [  1, 142,  77]],
   
          [[  1, 142,  72],
           [  1, 142,  79]],
   
          [[  1, 142,  75],
           [  1, 142,  82]]])

I would like to save it to a webp file and check if I can recover the result.

Attempt I

# save:
Image.fromarray(res.astype(np.uint8), mode='RGB').save("test.webp", "WEBP")
# check result:
np.array(Image.open("test.webp"))

This outputs:

array([[[  2, 143,  75],
        [  2, 143,  75]],

       [[  2, 143,  75],
        [  2, 143,  75]],

       [[  2, 143,  75],
        [  2, 143,  75]],

       [[  2, 143,  75],
        [  2, 143,  75]]], dtype=uint8)

Attempt failed, as these aren't the same numbers as I started with in res.

Attempt II

Now without .astype(np.uint8):

# save:
Image.fromarray(res,mode='RGB').save("test.webp", "WEBP")
# check result:
np.array(Image.open("test.webp"))

This outputs:

array([[[ 2,  5, 31],
        [ 0,  0, 27]],

       [[17, 21, 40],
        [ 0,  0, 15]],

       [[ 0,  0,  3],
        [25, 32, 34]],

       [[ 0,  8,  1],
        [ 0,  7,  0]]], dtype=uint8)

This is even worse than Attempt I.

How can I save a numpy array to a webp file?


Solution

  • Try saving your WEBP losslessly if you want the exact same values back, e.g. something like:

    im.save('im.webp', lossless=True)
    

    The specifics of what each file format can handle are documented here.