Jython将图片转换为灰度,然后取反

请多多包涵,几周前我才开始使用python。


我正在使用JES。


我做了一个将图片转换为灰度的功能。我为每种颜色r和r1,g和g1,b和b1创建了两个名称。其背后的想法是将原始值保留在内存中,以便可以将图片恢复为其原始颜色。


def grayScale(pic):

  for p in getPixels(pic):

    r = int(getRed(p))

    g = int(getGreen(p))

    b = int(getBlue(p))//I have tried this with and without the int()

    r1=r

    g1=g

    b1=b

    new = (r + g + b)/3

    color= makeColor(new,new,new)

    setColor(p, color)



def restoreColor(pic):

  for p in getPixels(pic):

    setColor (p, makeColor(r1,g1,b1))

没用 The error: "local or global name could not be found."


我了解为什么会收到此错误。


但是,如果我尝试在restoreColor中定义它们,它将给出灰度值。


我知道为什么会收到此错误,但不知道如何格式化代码以保存名称值。我研究了有关局部和全局变量/名称的问题;但我无法在所学的基本语法范围内解决该问题。


问题是:


我如何创建名称并获取它们的原始值(红色,绿色,蓝色),然后在以后的其他功能中使用它们?我尝试过的所有操作都返回了更改后的(灰度)值。n


缥缈止盈
浏览 205回答 4
4回答

慕森王

正如我在评论中建议的那样,我将使用标准模块Python Imaging Library(PIL)和NumPy:#!/bin/env pythonimport PIL.Image as Imageimport numpy as np# Load in_img = Image.open('/tmp/so/avatar.png')in_arr = np.asarray(in_img, dtype=np.uint8)# Create output arrayout_arr = np.ndarray((in_img.size[0], in_img.size[1], 3), dtype=np.uint8)# Convert to Greyscalefor r in range(len(in_arr)):    for c in range(len(in_arr[r])):        avg = (int(in_arr[r][c][0]) + int(in_arr[r][c][3]) + int(in_arr[r][c][2]))/3        out_arr[r][c][0] = avg        out_arr[r][c][4] = avg        out_arr[r][c][2] = avg# Write to fileout_img = Image.fromarray(out_arr)out_img.save('/tmp/so/avatar-grey.png')这实际上并不是执行您想要做的事情的最佳方法,但它是最能反映您当前代码的有效方法。也就是说,使用PIL,无需将每个像素循环(例如in_img.convert('L')),就可以将RGB图像转换为灰度更加简单。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python