I have been asked to create a mean_filter function on a 1-D array with given kernel, assuming zero padding.
A mean filter is an algorithm meant to remove noise. It takes an array, a kernel (say K), and replaces each value of the array by the mean of surrounding K values, itself inclusive.
This algorithm is used in image processing.
I was able to do this-
def mean_filter(arr, k):
# applies mean filter to 1-d array with the kernel size 2k+1 . Write your code here
p=len(arr)
arr2=np.zeros(2*k+p, dtype=float)
arr3=np.zeros(2*k+p, dtype=float)
arr4=np.zeros(p, dtype=float)
for i in range(p):
arr2[k+i]=arr[i]
for i in range(k,k+p):
sum=0
for j in range(-k,k+1):
sum+=arr2[i+j]
arr3[i]=sum/float(2*k+1)
for i in range(p):
arr4[i]=arr3[k+i]
return arr4
But what they expect from me is to do this without any kind of loops.
The instruction reads- "This task should be accomplished without any kind of loops, comprehensions or functions like np.vectorize, etc.
Do not use inbuilt convolve functions for this task"
I have literally no clue how to do this. Could you suggest something? Clues would be appreciated.
By example:
import numpy as np
k=2
kern=np.ones(2*k+1)/(2*k+1)
arr=np.random.random((10))
out=np.convolve(arr,kern, mode='same')