使用 NumPy 而不是 for 循环基于 A(透明)Chanel 组合两个 RGBA 图像

Combine two RGBA images based on A(transparent) Chanel using NumPy instead of for loop

我有两张 RGBA 颜色类型的图像,我想根据透明通道将它们组合起来我使用独占 for 循环编写代码,但我想使用 NumPy 以实现速度

crop = img[y:y+height,x:x+width,:].copy()
for i in range(0,height):
    for j in range(0,width):
        if(crop[i,j,3]  < resized_box[i,j,3]):
            crop[i,j,:] = resized_box[i,j,:]
img[y:y+height,x:x+width,:] = crop

你可以这样做:

# NOTE: I'm assuming x, y, width and height are defined somewhere and width, height match resized_box's shape
where_to_overwrite = img[y:y+height,x:x+width,3] < resized_box[:,:,3]
img[y:y+height,x:x+width,:][where_to_overwrite] = resized_box[where_to_overwrite]

基本上,首先您确定需要覆盖的像素索引(根据您的代码,这似乎是作物的 alpha 通道低于 resized_box 的像素),然后你实际设置值。

我认为第二个中的 double-indexing 是必要的,因为首先要查看裁剪图,然后使用计算的布尔索引来识别其中的特定像素。