简体   繁体   English

将2D numpy蒙版应用于灰度图像

[英]Applying a 2D numpy mask to grayscale image

I have a 256×256 px 2D mask with pixel values of either 0 or 255, and a matching grayscale image. 我有一个256×256像素的2D蒙版,其像素值为0或255,以及一个匹配的灰度图像。 Both have shapes (256, 256). 两者都有形状(256,256)。

I'd like to apply the mask on the grayscale image so the resulting image only contains pixels from the original grayscale image, where corresponding mask values are 255 (the original grayscale pixel values should be preserved). 我想在灰度图像上应用蒙版,因此生成的图像仅包含原始灰度图像中的像素,其中相应的蒙版值为255(应保留原始灰度像素值)。

I'm not being able to do this using 我无法使用

img_clean = img_grayscale[mask]

as it adds a new dimension to the array (as mentioned in numpy's docs). 因为它为数组增加了新的维度(如numpy的文档所述)。

How do I resolve this? 我该如何解决?

Just to add a 3rd option and modify your gray scale image inplace : 只需添加第三个选项并就地修改您的灰度图像:

img_grayscale[mask == 255] = 0

PS: you can just create a copy if you don't want in-place modifications. PS:如果您不想就地修改,则只能创建一个副本。

I think this should do the job 我认为这应该做的

np.where(mask == 255, img_grayscale, 0)

See https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html for documentation. 有关文档,请参见https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

A bitwise AND can be used to in order to set the pixel values to 0 where the mask is 0 : 可以使用按位AND来将像素值设置为0 ,其中mask为0

img_clean = img_grayscale & mask

As the mask contains either 0 or 255 values are either kept the same or set to 0 as per your requirements. 由于掩码包含0255 ,因此根据您的要求,值可以保持不变或设置为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM