From d871ef51dfbbea1ce16359b37ee26bce9fb939e1 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 6 Aug 2022 19:52:02 +1000 Subject: [PATCH] Restored __array__ for libraries that do not support __array_interface__ --- Tests/test_image_array.py | 7 +++++++ src/PIL/Image.py | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/Tests/test_image_array.py b/Tests/test_image_array.py index 7e5fd6fe1..5e1b4087d 100644 --- a/Tests/test_image_array.py +++ b/Tests/test_image_array.py @@ -94,3 +94,10 @@ def test_fromarray_palette(): # Assert that the Python and C palettes match assert len(out.palette.colors) == len(out.im.getpalette()) / 3 + + +def test_array(): + i = im.convert("L") + a = numpy.array(i) + + assert (a == i.__array__()).all() diff --git a/src/PIL/Image.py b/src/PIL/Image.py index 4eb2dead6..73a345b46 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -671,6 +671,11 @@ class Image: raise ValueError("Could not save to PNG for display") from e return b.getvalue() + def __array__(self, dtype=None): + import numpy as np + + return np.array(self, dtype) + @property def __array_interface__(self): # numpy array interface support