gpt4 book ai didi

python - 查找图像中的零像素,而不计算非零像素附近的像素

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:56 26 4
gpt4 key购买 nike

我有一个非常大的图像,其中有大片零像素区域和散布有零像素数据的区域。我想标记不在数据区域内的所有零像素 ( see image )。通常使用 np.where(data == 0) 可以工作,但这显然包括带有数据的区域。我尝试使用一种方法,列出每个零像素并找到具有非零邻居的像素,但这需要很长时间。数据相当大,如果可能的话,我想找到一种快速的方法来做到这一点。我正在寻找的输出只是一个简单的掩码数组。

最佳答案

您可以使用scipy.ndimage.morphology.binary_dilation来标记所有非零像素及其所有邻居:

>>> import numpy as np
>>> from scipy.ndimage import morphology
>>>
>>> a = (np.random.random((10, 10)) < np.clip(np.exp(np.arange(-5, 5)), None, 0.8)).view(np.uint8)
>>> a
array([[1, 0, 0, 0, 1, 1, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 0, 1, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 1, 1, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 1, 1]], dtype=uint8)
>>>
>>> mask = morphology.binary_dilation(a)
>>> mask.view(np.uint8)
array([[1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 1, 1, 1, 1, 1]], dtype=uint8)

默认的“结构元素”(控制什么被视为邻居)有四个邻居,但您也可以指定 8 个或某个任意掩码。

关于python - 查找图像中的零像素,而不计算非零像素附近的像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com