The median filter takes in the neighbourhood the median color (see Median filter)

(to test the function below, you can use these input and output solutions)

import Image, ImageFilter
im = Image.open('image.ppm')
 
median = im.filter(ImageFilter.MedianFilter(3))
median.save('image2.ppm')