我想實現一個高斯濾波器。爲此,我使用內核3x3和圖像數組。我遇到的問題是爲數組的每個[i,j]元素定義一個子矩陣3x3。我在代碼中寫下了細節。圖像/高斯濾波器陣列上的內核矩陣3x3
import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt
imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png") #importing image of original size (1929, 1280)
imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant', constant_values=0) #add 1 column and 1 row of zeros to avoid the kernel of going outside the array. size is (1931, 1282)
imagen_nueva = np.empty((1931, 1282)) #the new image. the same size as the image I will filter
(dim_x,dim_y)=np.shape(imagen_real)
ker1 = np.array([[1/16, 1/8, 1/16], #3x3 kernel
[1/8, 1/4, 1/8],
[1/16, 1/8, 1/16]])
def multiplicar_entero():
global imagen_nueva
for i in range(1,dim_x): #the range starts from 1 to avoid the column and row of zeros, and ends before the last col and row of zeros
for j in range(1,dim_y):
imagen_entry = np.empty((3, 3)) #Main problem here: how do I define a 3x3 matrix for each entry?
valor = np.sum(imagen_entry*ker1) #Matrix 3x3 is filled with the elements around each [i, j] entry of the array
imagen_real[i, j] = valor
imagen_nueva = np.append(imagen_real[i, j], (1931, 1282)) #This is supposed to each new [i, j] entry to the new image
print("La imagen con el blur effect es la siguiente:\n")
multiplicar_entero() #calls function
plt.imshow(imagen_nueva) #Show new image
plt.gray()
plt.show()
很抱歉的長碼。並感謝您的幫助。
可否請你發佈你的要求更明確的問題?就我所知,你是否試圖自己實現一個卷積算子? – akilat90
是的。卷積函數 – angelustt
您是否知道['scipy.ndimage'具有高斯過濾器](https://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.ndimage.filters。 gaussian_filter.html)?那np.append'調用是否還能工作?它看起來根本不像你期望的那樣。 –