用于Python图像处理的类Blockproc函数

2024-10-01 09:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:这是一个图像,所以建议的(How can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function)对我来说不太合适

我有下面的matlab代码

fun = @(block_struct) ...
std2(block_struct.data) * ones(size(block_struct.data));

B=blockproc(im2double(Icorrected), [4 4], fun);

我想重新编写代码,但这次是用Python编写的。我已经安装了Scikit,我正努力解决这个问题

^{pr2}$

问题当然是我并没有像上面一样,在很多街区都应用std。在

我怎么能做这样的事?启动一个循环并尝试为每个X*X块调用函数?那我就不会保持原来的尺寸了。在

有没有其他更有效的方法?在


Tags: 代码图像numpy编辑datablockarrayprocess
2条回答

我做了以下事情

io.use_plugin('pil', 'imread')
a = io.imread('C:\Users\Dimitrios\Desktop\polimesa\\arizona.jpg')

B = np.zeros((len(a)/2 +1, len(a[0])/2 +1))


for i in xrange(0, len(a), 2):
    for j in xrange(0, len(a[0]), 2):
        x.append(a[i][j])
        if i+1 < len(a):
            x.append(a[i+1][j])
        if j+1 < len(a[0]):
           x.append(a[i][j+1])
        if i+1 < len(a) and j+1 < len(a[0]):
           x.append(a[i+1][j+1])
        B[i/2][j/2] = np.std(x)
        x[:] = []         

我认为这是正确的。在图像上迭代2,取每个相邻节点,将它们添加到一个列表中并计算std

编辑*稍后编辑4x4块。在

如果窗口中没有重叠,则可以根据需要重新调整数据形状:

求9x9数组的3x3个窗口的平均值。在

import numpy as np

>>> a
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8],
       [ 9, 10, 11, 12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23, 24, 25, 26],
       [27, 28, 29, 30, 31, 32, 33, 34, 35],
       [36, 37, 38, 39, 40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49, 50, 51, 52, 53],
       [54, 55, 56, 57, 58, 59, 60, 61, 62],
       [63, 64, 65, 66, 67, 68, 69, 70, 71],
       [72, 73, 74, 75, 76, 77, 78, 79, 80]])

找到新形状

^{pr2}$

沿第一轴和第三轴求平均值。在

>>> b.mean(axis = (1,3))
array([[ 10.,  13.,  16.],
       [ 37.,  40.,  43.],
       [ 64.,  67.,  70.]])
>>> 

4x4阵列的2x2个窗口:

>>> a = np.arange(16).reshape((4,4))
>>> window_size = (2,2)
>>> tuple(np.array(a.shape) / window_size) + window_size
(2, 2, 2, 2)
>>> b = a.reshape(2,2,2,2)
>>> b.mean(axis = (1,3))
array([[  2.5,   4.5],
       [ 10.5,  12.5]])
>>> 

如果窗口大小不均匀地划分为数组大小,它将不起作用。在这种情况下,您需要在窗口中进行一些重叠,或者如果您只希望重叠numpy.lib.stride_tricks.as_strided是一种可行的方法,一个通用的N-D函数可以在Efficient Overlapping Windows with Numpy找到


2d数组的另一个选项是sklearn.feature_extraction.image.extract_patches_2d和ndarray的-sklearn.feature_extraction.image.extract_patches。每一个操作数组的步进以生成补丁/窗口。在

相关问题 更多 >