Skip to main content
 首页 » 编程设计

python之JES中如何将图片的一部分做成灰度

2025年05月04日7JeffreyZhao

您好,我正在尝试使用我的代码,但似乎无法弄清楚如何将我的部分代码变成灰度。这是我的代码:

def grayScale(picture): 
      xstop=getWidth(picture)/2 
      ystop=getHeight(picture)/2 
      for x in range(0,xstop): 
          for y in range(0,ystop): 
          oldpixel= getPixel(picture,x,y) 
          colour=getColor(oldpixel) 
          newColor=(getRed(oldpixel),getGreen(oldpixel),getBlue(oldpixel))/3 
          setColor(picture,(newColor,newColor,newColor)) 
      repaint(picture) 
 
 
nP=makePicture(pickAFile()) 
show(nP) 

感谢任何帮助,真的很努力地理解这一点。再次感谢您的帮助!

显示的错误:

grayScale(nP) The error was: 'tuple' and 'int'

Inappropriate argument type. An attempt was made to call a function with a parameter of an invalid type. This means that you did something such as trying to pass a string to a method that is expecting an integer. Please check line 8 of /Users/enochphan/Desktop/test

请您参考如下方法:

这里有一些事情会给您带来麻烦:

  • 在 y for 循环之后缩进您的代码(我猜您希望遍历所有高度)。
  • 新颜色只是当前像素的平均值,因此您需要在除以三之前使用加法将它们相加。
  • setColor() 接受一个像素和一个颜色对象。您要更改的像素是 oldpixel,颜色对象是使用 makeColor() 创建的。

这是实现了所有修复的代码:

def grayScale(picture): 
      xstop=getWidth(picture)/2 
      ystop=getHeight(picture)/2 
      for x in range(0,xstop): 
          for y in range(0,ystop): 
            oldpixel= getPixel(picture,x,y) 
            colour=getColor(oldpixel) 
            newColor = (getRed(oldpixel)+getGreen(oldpixel)+getBlue(oldpixel))/3 
            setColor(oldpixel,makeColor(newColor,newColor,newColor)) 
      repaint(picture)