PIL 图像和 Numpy 数组的 IndexError(Alpha 通道混合)

IndexError with PIL Image and Numpy Array (Alpha Channel Blending)

我在尝试 运行 这个程序时遇到错误。它采用 'marked' 图像并将标记的 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' 偏移,因为标记在特定的矩形中

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

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

另见 image modes.