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?
if you are using PIL
greyscaleIm = Image.open(filename).convert("L")
http://effbot.org/imagingbook/introduction.htm
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(...
精彩评论