Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To convert a grayscale image to RGB image using PIL

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.

like image 452
Dhvani Shah Avatar asked Nov 29 '25 16:11

Dhvani Shah


1 Answers

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.

like image 98
Giacomo Catenazzi Avatar answered Dec 02 '25 04:12

Giacomo Catenazzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!