pyvips icon indicating copy to clipboard operation
pyvips copied to clipboard

Convenience methods for Pillow integration

Open jonashaag opened this issue 1 year ago • 4 comments

Proposal: Add convenience integration with PIL/Pillow, eg. converting back and forth. Something along the lines of

pyvips.Image.from_pil(pil_img)

and

vips_img.pil()  # -> PIL.Image.Image

Happy to contribute a first draft if this is accepted.

jonashaag avatar Jul 15 '24 08:07 jonashaag

Hi @jonashaag, sure this sounds useful. What would it add over going via numpy?

jcupitt avatar Jul 15 '24 09:07 jcupitt

Probably nothing on the technical side, just a few convenience methods.

jonashaag avatar Jul 15 '24 11:07 jonashaag

It should be pretty easy right now:

import PIL.Image
pil_image = PIL.Image.new('RGB', (60, 30), color = 'red')
image = pyvips.Image.new_from_array(pil_image)

and:

import pyvips
import PIL.Image
image = pyvips.Image.black(100, 100, bands=3)
pil_image = PIL.Image.fromarray(image.numpy())

I don't know what PIL does with image metadata, maybe there's a simple way to bring that over as well?

jcupitt avatar Jul 15 '24 12:07 jcupitt

You're right that it's already quite simple... my suggestion of from_pil is the same as new_from_array (it's just a bit confusingly named for that purpose), and my convenience method for the other direction would be

    def pil(self):
        try:
            from PIL import Image
        except ModuleNotFoundError as e:
            raise ModuleNotFoundError("Pillow must be installed") from e

        return Image.fromarray(self.numpy())

Honestly not sure anymore if it's worth adding this because it's a very thin wrapper...

jonashaag avatar Jul 17 '24 07:07 jonashaag