def medianFilter(source1, dest, k):
w = pmGetImageWidth(dest)
h = pmGetImageHeight(dest)
k2 = k/2
for x in range(w):
for y in range(h):
# Pull out vector to be sorted.
xstart = max(0, x-k2) # Be careful at the border
ystart = max(0, y-k2)
xend = min(w, xstart+k)
yend = min(h, ystart+k)
neighbors = []
for xx in range(xstart, xend):
for yy in range(ystart, yend):
neighbors.append(pmGetPixel(source1, xx, yy)[0])
index_of_median = len(neighbors)/2
neighbors.sort()
median = neighbors[index_of_median]
pmSetPixel(dest, x, y, median, median, median)
# An example call to filter the image in window 1,
# putting the result in window 2, using a 3x3 neighborhood:
medianFilter(1, 2, 3)