-3

I am trying to create a program that removes only the "r" and "b" of an image's rgb values, leaving an image of varying shades of green. Here is my code:

import matplotlib.pyplot as plt
from PIL import Image

im = Image.open('Image.jpg')
rgb_im = im.convert('RGB')
width, height = rgb_im.size
for x in range(width):
    for y in range(height):
        r, g, b = rgb_im.getpixel((x, y))
        im[x][y] = [0, g, 0, 255]

fig, ax = plt.subplots(1, 1)
ax.imshow(im, interpolation='none')
fig.show()

I am very new to programming and don't understand why my code is throwing this error:

AttributeError: __getitem__

Could anyone explain how to fix this or recommend a better solution? AttributeError: __getitem__

depperm
  • 10,606
  • 4
  • 43
  • 67
Minihoot
  • 11
  • 4
  • Can you give some more info? What is the full error? What line does it show on? – DJMcMayhem Feb 03 '16 at 18:11
  • 1
    Have you done any research on this? There are no doubt thousands of questions on stackoverflow pertaining to `AttributeError: __getitem__`. – Bryan Oakley Feb 03 '16 at 18:14
  • Without a line number I'm not sure what in your code is throwing this error, but `__getitem__` is a builtin function that is called when you use square brackets to get an item (like in a list or dict). [Python 2 Reference](https://docs.python.org/2/reference/datamodel.html#object.__getitem__), [Python 3 Reference](https://docs.python.org/3/reference/datamodel.html#object.__getitem__) – user812786 Feb 03 '16 at 18:14
  • You need to create an array, im is a `PIL.JpegImagePlugin.JpegImageFile` object, what are you trying to do? – Padraic Cunningham Feb 03 '16 at 18:16

1 Answers1

0

I'm going to guess that the error is on line:

im[x][y] = ...

which would be a problem if an Image.open() object does not support [] syntax (which is implemented by __getitem__).

If this is true, then the fix is probably:

rgb_im.setpixel(...)
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237