使用 Python 的二维数组(图像)中的像素邻居 [英] Pixel neighbors in 2d array (image) using Python

查看:43
本文介绍了使用 Python 的二维数组(图像)中的像素邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 numpy 数组:

I have a numpy array like this:

x = np.array([[1,2,3],[4,5,6],[7,8,9]])

我需要使用以下输入参数创建一个函数,让我们将其称为邻居":

I need to create a function let's call it "neighbors" with the following input parameter:

  • x:一个 numpy 二维数组
  • (i,j):二维数组中元素的索引
  • d:邻域半径

作为输出,我想获得具有给定距离 d 的单元格 i,j 的邻居.所以如果我运行

As output I want to get the neighbors of the cell i,j with a given distance d. So if I run

neighbors(im, i, j, d=1) with i = 1 and j = 1 (element value = 5) 

我应该得到以下值的索引:[1,2,3,4,6,7,8,9].我希望我说清楚.有没有像 scipy 这样的库可以处理这个问题?

I should get the indices of the following values: [1,2,3,4,6,7,8,9]. I hope I make it clear. Is there any library like scipy which deal with this?

我已经做了一些工作,但这是一个粗略的解决方案.

I've done something working but it's a rough solution.

def pixel_neighbours(self, p):

    rows, cols = self.im.shape

    i, j = p[0], p[1]

    rmin = i - 1 if i - 1 >= 0 else 0
    rmax = i + 1 if i + 1 < rows else i

    cmin = j - 1 if j - 1 >= 0 else 0
    cmax = j + 1 if j + 1 < cols else j

    neighbours = []

    for x in xrange(rmin, rmax + 1):
        for y in xrange(cmin, cmax + 1):
            neighbours.append([x, y])
    neighbours.remove([p[0], p[1]])

    return neighbours

我该如何改进?

推荐答案

EDIT: 啊废话,我的回答就是写im[id:i+d+1, jd:j+d+1].flatten() 但写的太难懂了 :)

EDIT: ah crap, my answer is just writing im[i-d:i+d+1, j-d:j+d+1].flatten() but written in a incomprehensible way :)

古老的滑动窗口技巧可能对这里有所帮助:

The good old sliding window trick may help here:

import numpy as np
from numpy.lib.stride_tricks import as_strided

def sliding_window(arr, window_size):
    """ Construct a sliding window view of the array"""
    arr = np.asarray(arr)
    window_size = int(window_size)
    if arr.ndim != 2:
        raise ValueError("need 2-D input")
    if not (window_size > 0):
        raise ValueError("need a positive window size")
    shape = (arr.shape[0] - window_size + 1,
             arr.shape[1] - window_size + 1,
             window_size, window_size)
    if shape[0] <= 0:
        shape = (1, shape[1], arr.shape[0], shape[3])
    if shape[1] <= 0:
        shape = (shape[0], 1, shape[2], arr.shape[1])
    strides = (arr.shape[1]*arr.itemsize, arr.itemsize,
               arr.shape[1]*arr.itemsize, arr.itemsize)
    return as_strided(arr, shape=shape, strides=strides)

def cell_neighbors(arr, i, j, d):
    """Return d-th neighbors of cell (i, j)"""
    w = sliding_window(arr, 2*d+1)

    ix = np.clip(i - d, 0, w.shape[0]-1)
    jx = np.clip(j - d, 0, w.shape[1]-1)

    i0 = max(0, i - d - ix)
    j0 = max(0, j - d - jx)
    i1 = w.shape[2] - max(0, d - i + ix)
    j1 = w.shape[3] - max(0, d - j + jx)

    return w[ix, jx][i0:i1,j0:j1].ravel()

x = np.arange(8*8).reshape(8, 8)
print x

for d in [1, 2]:
    for p in [(0,0), (0,1), (6,6), (8,8)]:
        print "-- d=%d, %r" % (d, p)
        print cell_neighbors(x, p[0], p[1], d=d)

这里没有做任何计时,但这个版本可能有合理的性能.

Didn't do any timings here, but it's possible this version has reasonable performance.

有关更多信息,请使用短语rolling window numpy"或sliding window numpy"搜索网络.

For more info, search the net with phrases "rolling window numpy" or "sliding window numpy".

这篇关于使用 Python 的二维数组(图像)中的像素邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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