在Python中为图像中的每个像素选择7 * 7个相邻像素的最快方法

时间:2017-07-26 13:02:34

标签: python numpy scipy scikit-learn scikit-image

需要将图像作为数组读取,并为每个像素选择7 * 7个相邻像素,然后重新整形并作为第一行训练集放置:

  import numpy as np
  from scipy import misc
  face1=misc.imread('face1.jpg') 

face1尺寸为(288, 352, 3),需要为每个像素找到7 * 7个相邻像素,因此49 * 3颜色然后将其重新整形为(1,147)数组并将其堆叠成数组对于所有像素,我采取了以下方法:

X_training=np.zeros([1,147] ,dtype=np.uint8)
for i in range(3, face1.shape[0]-3):
    for j in range(3, face1.shape[1]-3):
        block=face1[i-3:i+4,j-3:j+4]
        pxl=np.reshape(block,(1,147))
        X_training=np.vstack((pxl,X_training))

结果X_training形状为(97572, 147)

并且最后一行包含全部为零:

a = len(X_training)-1
X_training = X_training[:a]

上面的代码适用于一张图片,但Wall time: 5min 19s我有2000张图片,因此所有图片都需要很长时间。我正在寻找一种更快的方法来迭代每个像素并执行上述任务。

修改:enter image description here 对于每个像素face1[i-3 : i+4 ,j-3:j+4]

,这就是我所说的邻居像素

3 个答案:

答案 0 :(得分:5)

一种有效的方法是使用stride_tricks在图像上创建一个滚动窗口,然后将其展平:

import numpy as np

face1 = np.arange(288*352*3).reshape(288, 352, 3)  # toy data

n = 7  # neighborhood size

h, w, d = face1.shape
s = face1.strides

tmp = np.lib.stride_tricks.as_strided(face1, strides=s[:2] + s,
                                      shape=(h - n + 1, w - n + 1, n, n, d))
X_training = tmp.reshape(-1, n**2 * d)
X_training = X_training[::-1]  # to get the rows into same order as in the question

tmp是图片的5D视图,其中tmp[x, y, :, :, c]相当于颜色通道face1[x:x+n, y:y+n, c]中的neigborhood c

答案 1 :(得分:3)

以下是< 1s在我的笔记本电脑上:

import scipy as sp
im = sp.rand(300, 300, 3)

size = 3
ij = sp.meshgrid(range(size, im.shape[0]-size), range(size, im.shape[1]-size))
i = ij[0].T.flatten()
j = ij[1].T.flatten()

N = len(i)
L = (2*size + 1)**2
X_training = sp.empty(shape=[N, 3*L])

for pixel in range(N):
    si = (slice(i[pixel]-size, i[pixel]+size+1))
    sj = (slice(j[pixel]-size, j[pixel]+size+1))
    X_training[pixel, :] = im[si, sj, :].flatten()

X_training = X_training[-1::-1, :]

当我无法想到单行矢量化版本时,我总是有点难过,但至少对你来说速度更快。

答案 2 :(得分:3)

使用scikit-image:

import numpy as np
from skimage import util

image = np.random.random((288, 352, 3))
windows = util.view_as_windows(image, (7, 7, 3))

out = windows.reshape(-1, 7 * 7 * 3)