Skip to content

Commit

Permalink
Merge pull request #5572 from t-vi/__array__-dtype
Browse files Browse the repository at this point in the history
Make Image.__array__ take optional dtype argument
  • Loading branch information
radarhere committed Jul 5, 2021
2 parents 94ecb27 + 8d1b433 commit d43d446
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
7 changes: 7 additions & 0 deletions Tests/test_image_array.py
Expand Up @@ -14,6 +14,10 @@ def test(mode):
ai = numpy.array(im.convert(mode))
return ai.shape, ai.dtype.str, ai.nbytes

def test_with_dtype(dtype):
ai = numpy.array(im, dtype=dtype)
assert ai.dtype == dtype

# assert test("1") == ((100, 128), '|b1', 1600))
assert test("L") == ((100, 128), "|u1", 12800)

Expand All @@ -27,6 +31,9 @@ def test(mode):
assert test("RGBA") == ((100, 128, 4), "|u1", 51200)
assert test("RGBX") == ((100, 128, 4), "|u1", 51200)

test_with_dtype(numpy.float64)
test_with_dtype(numpy.uint8)

with Image.open("Tests/images/truncated_jpeg.jpg") as im_truncated:
with pytest.raises(OSError):
numpy.array(im_truncated)
Expand Down
4 changes: 2 additions & 2 deletions src/PIL/Image.py
Expand Up @@ -681,7 +681,7 @@ def _repr_png_(self):
raise ValueError("Could not save to PNG for display") from e
return b.getvalue()

def __array__(self):
def __array__(self, dtype=None):
# numpy array interface support
import numpy as np

Expand All @@ -700,7 +700,7 @@ def __array__(self):
class ArrayData:
__array_interface__ = new

return np.array(ArrayData())
return np.array(ArrayData(), dtype)

def __getstate__(self):
return [self.info, self.mode, self.size, self.getpalette(), self.tobytes()]
Expand Down

0 comments on commit d43d446

Please sign in to comment.