0
def scaleImage(image):
    """
    A function that takes an image and makes each pixel grayscale:
    the red, blue, green components are the average of the respective
    components in each original pixel.
    """

    pix = image.getPixels()

    # How can I condense the following loop?

    newimage = Image()
    for pixel in pix:
        newpixel = ((int(pixel[0]) + int(pixel[1]) + int(pixel[2]))/3,
                    (int(pixel[0]) + int(pixel[1]) + int(pixel[2]))/3,
                    (int(pixel[0]) + int(pixel[1]) + int(pixel[2]))/3,
                     int(pixel[3]))
        newimage.setPixels(newpixel)

    return newimage

My task is to write a function showScale() that asks the user for an image filename, then displays both that image and its grayscale version in a window.

def showScale():

    filename = raw_input("The name of the image file? ")
    picture = Image.open(filename)
    newpicture = Image.open(scaleImage(picture))
    newpicture.show()

Question1. Should I use cs1graphics module to make it work?

Question2. How should I change my code to answer my task?

3
  • 1
    Your title is very general. I think you should edit it to be more specific. Commented Mar 24, 2011 at 0:56
  • Your grayscaling algorithm is incorrect. It's a weighted average, not a mean. Commented Mar 24, 2011 at 1:12
  • @pynator: all the questions from hkus10 seems like homework... Commented Mar 24, 2011 at 9:23

2 Answers 2

4

if you are using PIL

greyscaleIm = Image.open(filename).convert("L")

http://effbot.org/imagingbook/introduction.htm

Sign up to request clarification or add additional context in comments.

Comments

-1

although it may be overkill depending on what your ultimate goal is. It is also possible to do it with opencv.

img = cv.LoadImage(image)
gray = cv.cvCreateImage ((img.width, img.height), 8, 1)
cv.cvCvtColor(img, gray, cv.CV_BGR2GRAY)

then show both with

cv.NamedWindow(...
cv.ShowImage(...

Comments

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.