我想創建一個高斯模糊矩陣。我從http://www.labri.fr/perso/nrougier/teaching/numpy/numpy.html向量化與numpy
修改代碼dev_data具有784個像素特徵的行,並且我希望模糊像素周圍的鄰居以及像素本身。當我們沿着外邊緣(第1行,-1,第1列,第-1行)時,丟棄任何超出邊界的鄰居。我不太清楚如何做這個丟棄。
代碼:
# Initialize a new feature array with the same shape as the original data.
blurred_dev_data = np.zeros(dev_data.shape)
#we will reshape the 784 feature-long rows into 28x28 matrices
for i in range(dev_data.shape[0]):
reshaped_dev_data = np.reshape(dev_data[i], (28,28))
#the purpose of the reshape is to use the average of the 8 pixels + the pixel itself to blur
for idx, pixel in enumerate(reshaped_dev_data):
pixel = np.mean(reshaped_dev_data[idx-1:idx-1,idx-1:idx-1] + reshaped_dev_data[idx-1:idx-1,idx:idx] + reshaped_dev_data[idx-1:idx-1,idx+1:] +
reshaped_dev_data[idx:idx,idx-1:idx-1] + reshaped_dev_data[idx:idx,idx:idx] + reshaped_dev_data[idx:idx,idx+1:] +
reshaped_dev_data[idx+1: ,idx-1:idx-1] + reshaped_dev_data[idx+1: ,idx:idx] + reshaped_dev_data[idx+1: ,idx+1:])
blurred_dev_data[i,:] = reshaped_dev_data.ravel()
我得到一個錯誤與指數:
ValueError: operands could not be broadcast together with shapes (0,0) (0,27)
這不是一個indexerror,所以我不太清楚我在做什麼錯在這裏/如何修理它。
編輯'reshaped_dev_data [idx-1:idx-1,idx-1:idx-1]'到'reshaped_dev_data [idx-1,idx-1]'等等。 – Divakar
謝謝。現在我得到了我期待的界限錯誤。你知道一個忽略出界指數的好方法嗎? –
我建議使用高斯模糊濾鏡,而不是 - https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.gaussian_filter.html – Divakar