Last active
January 4, 2022 15:47
-
-
Save RashidLadj/8bd70bcf5bc0ed3f2936f295798920bb to your computer and use it in GitHub Desktop.
Apply a length-k median filter to a 1D array x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import cv2 as cv | |
def medianFilter(x, k): | |
""" | |
Apply a length-k median filter to a 1D array x. | |
Boundaries are extended by repeating endpoints. | |
this is the equivalent of opencv Median for 2D array | |
""" | |
if k == 1 : | |
return x | |
assert k % 2 == 1, "Median filter length must be odd." | |
assert x.ndim == 1, "Input must be one-dimensional." | |
k2 = (k - 1) // 2 | |
y = np.zeros ((len (x), k), dtype=x.dtype) | |
y[:,k2] = x | |
for i in range (k2): | |
j = k2 - i | |
y[j:,i] = x[:-j] | |
y[:j,i] = x[0] | |
y[:-j,-(i+1)] = x[j:] | |
y[-j:,-(i+1)] = x[-1] | |
return np.median (y, axis=1) | |
x = np.array([5, 7, 6, 8, 7, 9, 8, 8, 7, 9, 7, 5, 4, 5, 4, 3, 2, 1, 0]).astype(np.uint8) | |
print(medianFilter(x, 5)) | |
print(cv.medianBlur(np.asarray([x]), 5)[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment