anibali / pywebp

Python bindings for WebP
MIT License
74 stars 24 forks source link

numpy array encode #26

Closed rosyapril closed 3 years ago

rosyapril commented 3 years ago

Hi,

I have a RGB image (read as an numpy array) and want to encode it with webp, then send it out through socket. Is it possible to encode this array with webp since its format is smaller? I saw this below, is it possible to access the data in buf with numpy array?

# Encode a PIL image to WebP in memory, with encoder hints
pic = webp.WebPPicture.from_pil(img)
config = WebPConfig.new(preset=webp.WebPPreset.PHOTO, quality=70)
buf = pic.encode(config).buffer()

Thanks!

anibali commented 3 years ago

I believe this is the function that you are looking for: numpy.frombuffer

array = np.frombuffer(buf, dtype=np.byte)
rosyapril commented 3 years ago

Hi,

Thanks. It works now. But it seems that encoding time is too slow, which takes 0.5s(2FPS). Can it be directly obtained from numpy array or opencv without PIL?

anibali commented 3 years ago

If you look at the code for from_pil you will see that it calls another function called from_numpy which you can use directly on numpy arrays with the appropriate layout: https://github.com/anibali/pywebp/blob/670aa4b9564e4bd3b6683a3a37e685be3ccd23e5/webp/__init__.py#L248-L255