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)

      INSTALL @lib$+"SORTLIB"
      Sort% = FN_sortinit(0,0)
 
      Width% = 200
      Height% = 200
 
      DIM out&(Width%-1, Height%-1)
 
      VDU 23,22,Width%;Height%;8,16,16,128
      *DISPLAY Lenagrey
      OFF
 
      REM Do the median filtering:
      DIM pix&(24)
      C% = 25
      FOR Y% = 2 TO Height%-3
        FOR X% = 2 TO Width%-3
          P% = 0
          FOR I% = -2 TO 2
            FOR J% = -2 TO 2
              pix&(P%) = TINT((X%+I%)*2, (Y%+J%)*2) AND &FF
              P% += 1
            NEXT
          NEXT
          CALL Sort%, pix&(0)
          out&(X%, Y%) = pix&(12)
        NEXT
      NEXT Y%
 
      REM Display:
      GCOL 1
      FOR Y% = 0 TO Height%-1
        FOR X% = 0 TO Width%-1
          COLOUR 1, out&(X%,Y%), out&(X%,Y%), out&(X%,Y%)
          LINE X%*2,Y%*2,X%*2,Y%*2
        NEXT
      NEXT Y%
 
      REPEAT
        WAIT 1
      UNTIL FALSE