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

标签 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 颜色然后将其 reshape 为(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]

最佳答案

一种有效的方法是使用 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 View ,其中 tmp[x, y, :, :, c] 相当于邻域 face1[x :x+n, y:y+n, c] 颜色 channel c.

关于python - 在 Python 中为图像中的每个像素选择 7*7 相邻像素的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45327829/

相关文章:

python - 如何将 numpy 数组从 Python 传递给 Golang 函数

python - 避免 numpy 为重载运算符分发操作

python - 解压缩通用数组的 numpy 数组形状

python - 共享只读数据是否复制到不同的进程以进行多处理?

python - Scipy ndimage median_filter 来源

c++ - 编织内联类型转换(python)

python - 如何使用以字符串形式给出的 Pandas 来计算事件的持续时间?

python - 如何恢复用户的地址服务器,将其放入变量中并在命令行中执行

python - python中的反向排序和argsort

python - 如何使用 bool 掩码在 pandas DataFrame 中用 nan 替换 'any strings'?