From e95b55acd4d600b793f069c3c1fb266ec9ebe202 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 31 Mar 2023 20:48:14 +1100 Subject: [PATCH 1/2] Document loss of palette when converting to NumPy --- src/PIL/Image.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 95f5a9bc175..cc0b90b1dc5 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3031,21 +3031,25 @@ def frombuffer(mode, size, data, decoder_name="raw", *args): def fromarray(obj, mode=None): """ Creates an image memory from an object exporting the array interface - (using the buffer protocol). + (using the buffer protocol):: + + from PIL import Image + import numpy as np + a = np.zeros((5, 5)) + im = Image.fromarray(a) If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. - If you have an image in NumPy:: + Pillow images can also be converted to arrays:: from PIL import Image import numpy as np im = Image.open("hopper.jpg") a = np.asarray(im) - Then this can be used to convert it to a Pillow image:: - - im = Image.fromarray(a) + When converting Pillow images to arrays however, only pixel values are + transferred. This means that P and PA mode images will lose their palette. :param obj: Object with array interface :param mode: Optional mode to use when reading ``obj``. Will be determined from From 485532c1f3c3cf146a37b88f81dd6a0ff077daf1 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Fri, 31 Mar 2023 21:00:28 +1100 Subject: [PATCH 2/2] Mention available pixel types when converting from NumPy --- src/PIL/Image.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/PIL/Image.py b/src/PIL/Image.py index cc0b90b1dc5..259616e2b16 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -3041,6 +3041,10 @@ def fromarray(obj, mode=None): If ``obj`` is not contiguous, then the ``tobytes`` method is called and :py:func:`~PIL.Image.frombuffer` is used. + In the case of NumPy, be aware that Pillow modes do not always correspond + to NumPy dtypes. Pillow modes only offer 1-bit pixels, 8-bit pixels, + 32-signed integer pixels and 32-bit floating point pixels. + Pillow images can also be converted to arrays:: from PIL import Image