需要将图像作为数组读取,并为每个像素选择 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 张图片,所以要对所有图片执行此操作需要很长时间。我正在寻找一种更快的方法来遍历每个像素并执行上述任务。
最佳答案
一种有效的方法是使用 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/