3

I am trying a code to convert a grayscale image to a RGB image format in python, but, a TypeError is raised every time I try to execute it.

My code is as follows:

from PIL import Image
path = "bw.jpg"

img = Image.open(path)
rgb = img.convert("RGB")
width,height = rgb.size

for x in range(width):
    for y in range(height):
        r, g, b = img.getpixel((x, y))
        value  = r* 299.0/1000 + g* 299.0/1000 + b * 299.0/1000
        value = int(value)
        rgb.putpixel ((x, y), value)
rgb.save("abc.png")

The error that I get is:

r, g, b = img.getpixel((x, y))

TypeError: 'int' object is not iterable

Any assistance would be really appreciable.

Dhvani Shah
  • 351
  • 1
  • 7
  • 17

1 Answers1

0

You are confusing the images and the values. With img you get the greylevels, so you should use this:

grey = img.getpixel((x, y))

or, because you convert img to rgb (with RGB values), you could also write:

r, g, b = rgb.getpixel((x, y))

But then, it seems you are going doing unneeded calculations (ok, probably this was just the broken part of the complete code).

The error: img.getpixel() will return a number (on BW images), and int is not iterable to be split into r, g, and b, so the error. But rgb.getpixel() return a list (length 3), which is iterable.

Giacomo Catenazzi
  • 8,519
  • 2
  • 24
  • 32