Skip to content

get error when show a picture(image) : 'numpy.ndarray' object has no attribute 'mask' #10616

Closed

Description

@NewThinker-Jeffrey

Hi

I was using python3.5.2, numpy 1.14.1, and matplotlib 2.1.2 and encountered a problem when I attempted to show a picture with pyplot. It always gave errors saying 'numpy.ndarray object has no attribute mask', and the related source code seemed in 'matplotlib/image.py'.

I'm not sure whether it was caused by matplotlib or numpy. How do I fix this ?

$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> from PIL import Image
>>> img=Image.open('test.jpg')
>>> imgfig = plt.figure()
>>> imgplt = imgfig.add_subplot(111)
>>> imgplt.imshow(img)
<matplotlib.image.AxesImage object at 0x7ff142877438>
>>> plt.show()
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 233, in resize
    self.show()
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 304, in draw
    FigureCanvasAgg.draw(self)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_agg.py", line 430, in draw
    self.figure.draw(self.renderer)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/figure.py", line 1299, in draw
    renderer, self, artists, self.suppressComposite)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 138, in _draw_list_compositing_images
    a.draw(renderer)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_base.py", line 2437, in draw
    mimage._draw_list_compositing_images(renderer, self, artists)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 138, in _draw_list_compositing_images
    a.draw(renderer)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 566, in draw
    renderer, renderer.get_image_magnification())
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 793, in make_image
    unsampled=unsampled)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 430, in _make_image
    if A.mask.shape == A.shape:
AttributeError: 'numpy.ndarray' object has no attribute 'mask'
Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.5/tkinter/__init__.py", line 1553, in __call__
    return self.func(*args)
  File "/usr/lib/python3.5/tkinter/__init__.py", line 599, in callit
    func(*args)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 323, in idle_draw
    self.draw()
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 304, in draw
    FigureCanvasAgg.draw(self)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_agg.py", line 430, in draw
    self.figure.draw(self.renderer)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/figure.py", line 1299, in draw
    renderer, self, artists, self.suppressComposite)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 138, in _draw_list_compositing_images
    a.draw(renderer)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_base.py", line 2437, in draw
    mimage._draw_list_compositing_images(renderer, self, artists)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 138, in _draw_list_compositing_images
    a.draw(renderer)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 55, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 566, in draw
    renderer, renderer.get_image_magnification())
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 793, in make_image
    unsampled=unsampled)
  File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 430, in _make_image
    if A.mask.shape == A.shape:
AttributeError: 'numpy.ndarray' object has no attribute 'mask'

Activity

  1. changed the title [-]get error 'numpy.ndarray' object has no attribute 'mask' when show a picture(image)[/-] [+]get error when show a picture(image) : 'numpy.ndarray' object has no attribute 'mask'[/+] on Feb 27, 2018
  2. efiring commented on Feb 27, 2018

    @efiring
    Member

    This looks like a bug that is still in master, based on code inspection. pil_to_array is returning a plain ndarray, but everything else going into the image data attribute is converted to a masked array, and subsequent code assumes that at least 2-D arrays are masked. The quickest fix would be for the output of pil_to_array to be converted to a masked array in the set_data method. Otherwise, one would have to look carefully at all possible code paths and ensure that they handle ndarrays and masked arrays equally.

  3. added this to the v2.2.0 milestone on Feb 27, 2018
  4. jklymak commented on Feb 27, 2018

    @jklymak
    Member

    OK, I'm almost in exactly this code block in #10613. I'll add to that PR if thats OK....

  5. jklymak commented on Feb 27, 2018

    @jklymak
    Member

    OK, I can't reproduce this on master.

    import matplotlib.pyplot as plt
    from PIL import Image
    img=Image.open('test.jpg')
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(img)
    
    plt.show()
    

    works fine.

  6. NewThinker-Jeffrey commented on Feb 27, 2018

    @NewThinker-Jeffrey
    Author

    Hi @jklymak

    Have you tried this code on branch v2.1.2 ? And do you get the same errors with me? If not, the problem may be caused by myself and I'll handle it later (it's not urgent to me and I don't have time to dig into it today).
    I don't want to waste your time because of my own mistake.

  7. efiring commented on Feb 27, 2018

    @efiring
    Member

    I wonder whether it depends on the type of jpg file. @NewThinker-Jiwey can you supply the example you used? I think that the jpg can be returned as a 2-D array or a 3-D array, and the problem would be with the former. Again, this is just based on looking fairly quickly at the code.

  8. jklymak commented on Feb 27, 2018

    @jklymak
    Member

    Yeah, its also possible my pillow and numpy are a bit old... I'll check soon

  9. jklymak commented on Feb 27, 2018

    @jklymak
    Member

    numpy 1.14 and matplotlib 2.1.2 I can't get this to trigger on a generic jpg.

  10. NewThinker-Jeffrey commented on Feb 27, 2018

    @NewThinker-Jeffrey
    Author
  11. efiring commented on Feb 27, 2018

    @efiring
    Member

    With that file I can reproduce it. It is a monochrome file, so it is coming through as a 2-D array and going through the color-mapping code path. That's where it is being assumed to be a masked array.

  12. efiring commented on Feb 27, 2018

    @efiring
    Member

    The quick fix would be here (in image.py with line numbers):

        607     def set_data(self, A):
        608         """
        609         Set the image array.
        610
        611         ACCEPTS: numpy/PIL Image A
        612
        613         Note that this function does *not* update the normalization used.
        614         """
        615         # check if data is PIL Image without importing Image
        616         if hasattr(A, 'getpixel'):
        617             self._A = pil_to_array(A)
        618         else:
        619             self._A = cbook.safe_masked_invalid(A, copy=True)
    

    changing line 617 to

        self._A = np.ma.array(pil_to_array(A))
    

    Untested, and it might not be the best way to fix it.

  13. NewThinker-Jeffrey commented on Feb 27, 2018

    @NewThinker-Jeffrey
    Author

    @efiring Got it, thanks !!
    For workaround I can show the pic by convert it to RGB beforehand:

    import matplotlib.pyplot as plt
    from PIL import Image
    img=Image.open('test.jpg').convert('RGBA')
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(img)
    
    plt.show()
  14. jklymak commented on Feb 27, 2018

    @jklymak
    Member

    @efiring - that will indeed allow the image to be plotted, but it will be coloured w/ the default colormap (and linear norm), rather than displayed as greyscale, which I assume most folks who use PIL would want?

    I've fixed in #10613 as:

        if hasattr(A, 'getpixel'):
                if A.mode == 'L':
                    # greyscale image, but our logic assumes rgba:
                    self._A = pil_to_array(A.convert('RGBA'))
                else:
                    self._A = pil_to_array(A)

    I didn't change pil_to_array since its technically correct to convert to a 2-D array, but it just doesn't work w/ imshow.

  15. efiring commented on Feb 27, 2018

    @efiring
    Member

    Thanks, that makes perfect sense.

  16. jpambrun commented on Mar 1, 2018

    @jpambrun

    I can work around the issue by converting the PIL image to a numpy array (e.g. plt.imshow(np.array(im1), cmap="gray")).

    The proposed fix will show up correctly, but the pixel probe will show the four RGBA values instead of the usual single intensity value. Also, saving the figure may result in the wrong format being used?

  17. jklymak commented on Mar 2, 2018

    @jklymak
    Member

    @jpambrun Sure, you can also display the image that way. But matplotlib will still save the resulting image as RGBA, so I don't think converting to RGBA at this step hurts anything, and saves the user from having to supply a colormap.

  18. tacaswell commented on Mar 3, 2018

    @tacaswell
    Member

    Closed by #10613

  19. added a commit that references this issue on Apr 23, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions