需要将图像读取为数组,并对每个像素选择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张图像,所以需要很长时间才能完成所有的图像。我正在寻找一个更快的方法来迭代每一个像素,并完成上述任务。
编辑:

这就是我所说的相邻像素,对于每一个像素face1[i-3 : i+4 ,j-3:j+4]
发布于 2017-07-26 13:42:18
一种有效的方法是使用stride_tricks在图像上创建一个2d滚动窗口,然后将其压平:
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 questiontmp是进入图像的5D视图,其中tmp[x, y, :, :, c]等价于彩色通道c中的邻接face1[x:x+n, y:y+n, c]。
发布于 2017-07-26 13:42:10
以下是我的笔记本电脑上的< 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, :]当我想不出一行矢量化的版本时,我总是有点难过,但至少对你来说更快。
发布于 2017-08-02 20:41:00
使用scikit-图像:
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)https://stackoverflow.com/questions/45327829
复制相似问题