【问题标题】:IndexError with PIL Image and Numpy Array (Alpha Channel Blending)PIL 图像和 Numpy 数组的 IndexError(Alpha 通道混合)
【发布时间】:2016-03-14 04:57:43
【问题描述】:

我在尝试运行此程序时遇到错误。它采用“标记”图像并将标记的 RGB 值与原始图像的 RGB 值混合。它使用 PIL 和 Numpy 使用图像的 Alpha 通道值混合两个几乎相同图像的 RGB 值。我遇到的错误是:

File "wip.py", line 87, in mark
apixel[channel] = ((apixel[channel]*(apixel[3]/255))+(oapixel[channel]*(oapixel[3]/255)))/2
IndexError: index 3 is out of bounds for axis 0 with size 3

而相关代码为:

img = np.array(marked)
orig_img = np.array(original_image)
for x in range(wmark_w):
    for y in range(wmark_h):
        if img[x][y][3] < 255:
            apixel = img[x][y]
            oapixel = orig_img[x+int(0.02*width)][y+int(0.02*width)]
            for channel in range(4):
                apixel[channel] = ((apixel[channel]*(apixel[3]/255))+(oapixel[channel]*(oapixel[3]/255)))/2
marked = PIL.Image.fromarray(img)
del img; del orig_img

'oapixel' 是偏移的,因为标记位于特定的矩形中

【问题讨论】:

    标签: python numpy python-imaging-library


    【解决方案1】:

    显然原始图像不是 RGBA 格式。将其转换为:

    orig_img = np.array(original_image.convert('RGBA'))
    

    另见image modes.

    【讨论】:

    • 这解决了我原来的错误,但现在我得到了一个类似的错误:File "wip.py", line 85, in mark if img[x][y][3] &lt; 255: IndexError: index 640 is out of bounds for axis 0 with size 640 640 将根据我使用的水印的分辨率更改为不同的数字。
    • @L.Teder - 该错误意味着x 索引超出了图像尺寸。你怎么得到wmark_wwmark_h
    • @L.Teder - 啊,我想我看到了问题:与索引 PIL 图像相比,索引 numpy 数组是相反的。所以无论你在哪里索引一个array,第一个索引应该是y,第二个应该是x。另外顺便说一句,出于样式和性能的原因,您应该使用元组而不是连续的括号来索引 numpy 数组。所以img[x][y][channel] 写成img[y,x,channel]
    • 现在我得到一个(再次)类似的错误:File "wip.py", line 85, in mark if img[x][y][3] &lt; 255: IndexError: index 498 is out of bounds for axis 1 with size 498 498 更改了水印的分辨率,但与之前的第 85 行 IndexError 不同。顺便说一句,感谢您的所有帮助。
    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2018-11-22
    相关资源
    最近更新 更多