在Numpy数组中创建缓冲区 [英] Create buffer zone within a Numpy array

查看:152
本文介绍了在Numpy数组中创建缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二进制图像,如下所示:

I have a binary image as follows:

data = np.array([[0, 0 , 0 , 0 , 0 , 0 , 0 , 0],
                 [0, 0 , 0 , 0 , 0 , 0 , 0 , 0],
                 [0, 0 , 1 , 1 , 1 , 1 , 0 , 0],
                 [0, 0 , 1 , 1 , 1 , 1 , 0 , 0],
                 [0, 0 , 1 , 1 , 1 , 1 , 0 , 0],
                 [0, 0 , 0 , 0 , 0 , 0 , 0 , 0],
                 [0, 0 , 0 , 0 , 0 , 0 , 0 , 0]])

对于具有1s值的像素,我想使两个像素的缓冲区分别在每个四个方向上具有1s值.预期结果将是:

For pixels having 1s values, I want to make buffer zone of two pixels with value 1s surrounded in every four directions. The expected result would be:

result=np.array([[1, 1 , 1 , 1 , 1 , 1 , 1 , 1],
                 [1, 1 , 1 , 1 , 1 , 1 , 1 , 1],
                 [1, 1 , 1 , 1 , 1 , 1 , 1 , 1],
                 [1, 1 , 1 , 1 , 1 , 1 , 1 , 1],
                 [1, 1 , 1 , 1 , 1 , 1 , 1 , 1],
                 [1, 1 , 1 , 1 , 1 , 1 , 1 , 1],
                 [1, 1 , 1 , 1 , 1 , 1 , 1 , 1]])

我该怎么办?

推荐答案

如果输入和输出数组上只有1和0,则可以使用2D卷积来完成,这很简单而且可行.

If you only have ones and zeros on the input and output array, you can do it with a 2D convolution, which is simple and works.

from scipy.signal import convolve2d

data = np.array([[0, 0 , 0 , 0 , 0 , 0 , 0 , 0],
                 [0, 0 , 0 , 0 , 0 , 0 , 0 , 0],
                 [0, 0 , 1 , 1 , 1 , 1 , 0 , 0],
                 [0, 0 , 1 , 1 , 1 , 1 , 0 , 0],
                 [0, 0 , 1 , 1 , 1 , 1 , 0 , 0],
                 [0, 0 , 0 , 0 , 0 , 0 , 0 , 0],
                 [0, 0 , 0 , 0 , 0 , 0 , 0 , 0]])

# the kernel doesn't need to be ones, it just needs to be positive and
# non-zero.
kernel = np.ones((5, 5))

result = np.int64(convolve2d(data, kernel, mode='same') > 0)

这将为您提供所需的输出.您需要定义要在边缘发生的事情-在此版本中,输出数组的大小与输入数组的大小相同.

Which gives you the output you want. You need to define what you want to happen at the edges - in this version, the output array is the same size as the input array.

如果数组稀疏,则可能可以更快地执行某些操作.

It might be possible you can do something faster if you have a sparse array.

如果数组中的值不是1和0,则需要更多考虑.

If you have other values than one and zero in your array, more thought would be needed.

这篇关于在Numpy数组中创建缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆