2

I have a question on how do I calculate the value of a pixel.

For example I take 3x3 pixels and need to order and select the pixel[4] to apply the median filter.

How do I calculate the value of those pixels to order then?

Do I order each channel (R G B) and then select the middle term of each and put the value into to the pixel?

Or I have to sum the 3 channels?

I found online a code with PIL on python, but I don't understand how the "members.sort()" function works

def FiltroMediana(path):

img = Image.open(path)
members = [(0, 0)] * 9
width, height = img.size
newimg = Image.new("RGB", (width, height), "white")
for i in range(1, width - 1):
    for j in range(1, height - 1):
        members[0] = img.getpixel((i - 1, j - 1))
        members[1] = img.getpixel((i - 1, j))
        members[2] = img.getpixel((i - 1, j + 1))
        members[3] = img.getpixel((i, j - 1))
        members[4] = img.getpixel((i, j))
        members[5] = img.getpixel((i, j + 1))
        members[6] = img.getpixel((i + 1, j - 1))
        members[7] = img.getpixel((i + 1, j))
        members[8] = img.getpixel((i + 1, j + 1))
        members.sort()
        newimg.putpixel((i, j), (members[4]))

newimg.save("MedianFilterPIL.png", "PNG")
newimg.show()
Miki
  • 40,887
  • 13
  • 123
  • 202
Mark4
  • 21
  • 3
  • The sort function call is [pythons list.sort()](https://www.geeksforgeeks.org/python-list-sort/) command. It simply orders the list after adding in 8 entries – GPPK Feb 26 '19 at 13:20
  • In case anyone is feeling really keen... https://www.comm.utoronto.ca/~kostas/Publications2008/pub/proceed/38.pdf – Mark Setchell Feb 26 '19 at 16:08
  • There is a generic filter module by the way that gives you all the framework of the loops and passes you all the surrounding pixels by the way. I used it here https://stackoverflow.com/a/54440152/2836621 for a modal filter, but you only need to change one line to make it a median filter. – Mark Setchell Feb 26 '19 at 16:11

1 Answers1

2

There is no "nice" way to apply a median filter to a color image.

  • filtering the three planes separately creates new colors that weren't in the image,

  • true color filtering is achieved by finding the color that minimizes the total distance to the others; but this is time consuming.