5

I am using the following code to convert a color image to a grayscale image. Why does it throw a TypeError?

#!/usr/bin/python
from PIL import Image
im = Image.open("Penguins.jpg")
pixel = im.load()
width, height = im.size
for x in range(width):
    for y in range(height):
        R,G,B = pixel[x,y]
        pixel[x,y] = ((0.299*R+0.587*G+0.114*B),(0.299*R+0.587*G+0.114*B),(0.299*R+0.587*G+0.114*B))

im.save("Penguins_new.jpg")
3
  • 2
    Have you considered that you are passing a float and not an integer? Commented Apr 10, 2015 at 18:48
  • 2
    I know but how should I do to make it correct? Commented Apr 10, 2015 at 18:52
  • Have a look at my answer. It will hopefully solve your solution. Commented Apr 10, 2015 at 18:53

1 Answer 1

9

The argument that you are passing to pixel[x, y] needs to be an int, not a float. Try casting it as an integer.

pixel[x, y] = ((int(0.299*R) + int(...
Sign up to request clarification or add additional context in comments.

9 Comments

but the question is float ~"~
That's not a cast; it's a constructor call. Python doesn't have casts.
You can think of it as a conversion then. And then the same can be said for that python doesn't have constructors either. People use different terminology. Don't start a war, just keep it simple. And, also, the reason that you are getting the error, is because the function does not want a float, but rather an integer. So you can't pass a float, you have to pass an integer.
If I want to pass a float, what function should I use?
@BlacklightShining Also, that has to do with classes, not types. You should figure out the difference between the two.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.