如何在Python中缩放图像?
我的任务是编写一个函数showScale(),要求用户输入图像文件名,然后在窗口中显示该图像及其灰度版本如何在Python中缩放图像?,python,Python,我的任务是编写一个函数showScale(),要求用户输入图像文件名,然后在窗口中显示该图像及其灰度版本 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 origin
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
问题1。我应该使用cs1graphics模块使其正常工作吗
问题2。如何更改代码以回答任务?如果您正在使用
greyscaleIm=Image.open(filename.convert(“L”)
如果您正在使用
greyscaleIm=Image.open(filename.convert(“L”)
尽管根据你的最终目标可能有点过分。也可以使用opencv进行此操作
def showScale():
filename = raw_input("The name of the image file? ")
picture = Image.open(filename)
newpicture = Image.open(scaleImage(picture))
newpicture.show()
然后,用
img = cv.LoadImage(image)
gray = cv.cvCreateImage ((img.width, img.height), 8, 1)
cv.cvCvtColor(img, gray, cv.CV_BGR2GRAY)
尽管这可能有点过分,取决于你的最终目标是什么。也可以使用opencv进行此操作
def showScale():
filename = raw_input("The name of the image file? ")
picture = Image.open(filename)
newpicture = Image.open(scaleImage(picture))
newpicture.show()
然后,用
img = cv.LoadImage(image)
gray = cv.cvCreateImage ((img.width, img.height), 8, 1)
cv.cvCvtColor(img, gray, cv.CV_BGR2GRAY)
你的头衔很笼统。我认为你应该把它编辑得更具体一些。你的灰度算法不正确。这是加权平均数,不是平均数。@pynator:香港大学10年级的所有问题似乎都是家庭作业……你的题目很笼统。我认为你应该把它编辑得更具体一些。你的灰度算法不正确。这是加权平均数,不是平均数。@pynator:所有来自香港大学10年级的问题似乎都是家庭作业。。。