python - 无法从 image.load() 写入 Python 数据结构

标签 python python-imaging-library

我正在做类作业,但在使用 Python 中的图像上的 load() 函数生成的数据结构方面遇到了问题。我在这里所做的就是尝试将整个图像从 RGB 转换为 HSL。问题是,当我尝试将新值写回数据结构时,它们不会被写入。然而,我已经在代码的其他地方成功地写入了这种类型的结构。如果不是这种情况,我会假设该结构是不可变的,但看起来并非如此。如果有人可以向我解释发生了什么以及这个特定的数据结构如何工作,我将非常感激。我怀疑我需要以某种方式创建一个新的结构来写入函数中,但除了创建一个新图像并从中获取结构之外,我不知道如何做。

def toHSL(px):     #reorders values to h, s, l from h, l, s
    for x in xrange(0, dim[0]):
        for y in xrange(0, dim[1]):
            r, g, b = px[x,y][0], px[x,y][1], px[x,y][2]   #I don't really understand how to create this type of data structure, even
            r, g, b = [x/255.0 for x in r, g, b]           #Python uses values from 0 to 1
            h, l, s = colorsys.rgb_to_hls(r, g, b)
            px[x,y] = (int(h*255), int(s*255), int(l*255)) #trying to save back to the original data structure
    return px

img_name = "Mandrill"

try:
    im = Image.open(img_name + ".bmp")
except:
    print "Unable to load image."
    sys.exit()
dim = im.size
pix = im.load()
new = Image.new("RGB", dim)
newpx = new.load()

hsl = toHSL(pix)
print hsl[0,0][0], hsl[0,0][1], hsl[0,0][2]    #<< gives the original values

最佳答案

我的立场是正确的,显然可以使用该(未记录的)索引技术来读取和写入像素,至少对于某些图像格式是这样。每天学习新东西...;-)

无论如何,你的程序有问题的是这行:

    r, g, b = [x/255.0 for x in r, g, b]

它更改已用于迭代像素坐标的x值。只需将其更改为另一个变量名称(如下所示)即可使您的代码执行您想要的操作:

    r, g, b = [c/255.0 for c in r, g, b]

(注意,最好将其更改为以下内容并删除其前面的行)

    r, g, b = [c/255.0 for c in px[x,y]]

完成此操作后,将生成以下图像 — 显示为 RGB,而不是 HSL,以表明该结构确实是可变的:

output from correctly working code show image was changed

关于python - 无法从 image.load() 写入 Python 数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749092/

相关文章:

python - 如何用蓝色为 RGB 图像着色?

python - 将图像转换为不同类的 PIL

python - 如何在 form_valid 中获取对象 ID?

python - 将数据拟合到广义极值分布

python - 对 Python 3 中的多个项目使用相同的字符串格式

python - 如何在 Python 中生成许多 32x32 灰度图像的平均图像?

python - 使用 Python PIL 打开图像

macos - 在 Mac OS 下的 Python 2.7 中使用 Tkinter + Pillow (PIL) 时,PNG 图像不显示

python - 同一页面上相同 wtform 表单的多个独立实例

python - 类型错误 : 'str' object is not callable (I'm not calling it? )