Numpy其中ValueError -操作数无法与形状(x,y,z)一起广播

jjhzyzn0  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(116)

我试图使阿尔法通道在PNG的一个特定的价值观,根据其RGB值。为了简单起见,假设我只想平均每个像素的前3个值,然后基于此更改alpha值。

import numpy as np
# both image and avg are a (10, 10, 4)
img = np.random.rand(10, 10, 4)
avg = np.average(img[:, :, :-1], axis=2)
# the mask is a (10, 10)
mask = avg > .5
# np.full((img.shape[0], img.shape[1], 1), 255) creates a (10, 10, 1) array full of the value 255
# np.append(..., axis=2) appends the above so that each pixel will have a 255 at the end
# np.where(mask, ..., img) should use the mask to find each pixel, update that pixel to either use the alpha channel, if true, or keep its alpha channel, if false.  
np.where(mask, np.append(img[:, :, :-1], np.full((img.shape[0], img.shape[1], 1), 255), axis=2), img)

当前(正确地),它抛出错误-> ValueError:操作数无法与形状(10,10)(10,10,4)(10,10,4)一起广播。
如果我不得不尝试解释它,那是因为掩码是10 x 10,而要作用的值是10 x10 x4。那么有没有办法“绕过这个”;让true或false值返回一个具有正确值的像素?
我知道我可以用循环来做这件事,但我想在可能的地方使用numpy。
谢谢大家!

dl5txlt9

dl5txlt91#

正如您提到的,mask变量与img变量的维数不同。有很多方法可以避免这个问题,但是我推荐@bb1的建议来简化你的代码。将最后一行替换为

img[mask, -1] = 255

基本上,它会将满足遮罩(mask=True)的像素的最后一个通道(alpha通道)修改为255。否则,将保留现有alpha值。

相关问题