' numpy.ndarray'对象没有属性'模式'

时间:2017-05-20 19:47:11

标签: python numpy python-imaging-library

我的代码出错:

import PIL.ImageOps
inverted_image = PIL.ImageOps.invert(image)

追溯是

Traceback (most recent call last):
  File "filter.py", line 32, in <module>
    inverted_image = PIL.ImageOps.invert(denoise)
  File "/usr/lib/python3/dist-packages/PIL/ImageOps.py", line 367, in invert
    return _lut(image, lut)
  File "/usr/lib/python3/dist-packages/PIL/ImageOps.py", line 48, in _lut
    if image.mode == "P":
AttributeError: 'numpy.ndarray' object has no attribute 'mode'

我该如何解决?

1 个答案:

答案 0 :(得分:3)

如果您尝试在numpy.ndarray上执行ImageOps.invert,则会引发异常:

>>> import numpy as np
>>> from PIL import Image
>>> from PIL import ImageOps
>>> ImageOps.invert(np.ones((100, 100, 3), dtype=np.uint8))
AttributeError: 'numpy.ndarray' object has no attribute 'mode'

要解决此问题,您需要将其转换为Image

>>> img = Image.fromarray(np.ones((100, 100, 3), dtype=np.uint8))  # RGB image
>>> ImageOps.invert(img)
# works