From aa55f2546b186d27425d5d91f9c512d9d9035429 Mon Sep 17 00:00:00 2001 From: Amir MOHAMMADI <amir.mohammadi@idiap.ch> Date: Wed, 27 Apr 2022 16:54:16 +0200 Subject: [PATCH] Add bob_to_pillow and back conversion --- bob/io/image.py | 41 +++++++++++++++++++++++++++++++++++++++++ conda/meta.yaml | 2 ++ 2 files changed, 43 insertions(+) diff --git a/bob/io/image.py b/bob/io/image.py index 16ccb62..832225a 100644 --- a/bob/io/image.py +++ b/bob/io/image.py @@ -1,4 +1,5 @@ import numpy as np +from PIL import Image def to_matplotlib(img): @@ -45,6 +46,46 @@ def to_bob(img): return np.moveaxis(img, -1, -3) +def bob_to_pillow(img): + """Converts the floating or uint8 image to a Pillow Image. + + Parameters + ---------- + img : numpy.ndarray + A gray-scale or RGB color image in Bob format (channels first) + + Returns + ------- + Image + An object of pillow.Image. + """ + # first convert to matplotlib format + img = to_matplotlib(img) + # if img is floating point, convert to uint8 + if isinstance(img, np.floating): + # we expect float images to be between 0 and 1 + img = np.clip(img, 0, 1) * 255 + img = img.astype(np.uint8) + + return Image.fromarray(img) + + +def pillow_to_bob(img): + """Converts an RGB or gray-scale pillow image to Bob format + + Parameters + ---------- + img : Image + A Pillow Image + + Returns + ------- + numpy.ndarray + Image in Bob format + """ + return to_bob(np.array(img)) + + def opencvbgr_to_bob(img): """Returns a view of the image from OpenCV BGR format to Bob RGB format. This function works with images, batches of images, videos, and higher diff --git a/conda/meta.yaml b/conda/meta.yaml index 63f2cb2..2c121cf 100644 --- a/conda/meta.yaml +++ b/conda/meta.yaml @@ -24,11 +24,13 @@ requirements: - bob.extension - h5py {{ h5py }} - numpy {{ numpy }} + - pillow {{ pillow }} - imageio {{ imageio }} run: - python - setuptools - {{ pin_compatible('numpy') }} + - {{ pin_compatible('pillow') }} - {{ pin_compatible('imageio') }} - {{ pin_compatible('h5py') }} -- GitLab