proc medianfilter {image} {
    set w [image width $image]
    set h [image height $image]
    #-- read graylevels of image into list of lists matrix
    set data {}
    for {set i 0} {$i<$h} {incr i} {
        set row {}
        for {set j 0} {$j<$w} {incr j} {
            lappend row [lindex [$image get $j $i] 0]
        }
        lappend data $row
    }
    set res [image create photo -height $h -width $w]
    $res copy $image
    for {set i 1} {$i<$h-3} {incr i} {
        for {set j 1} {$j<$w-3} {incr j} {
            set pixels {}
            foreach k {-1 0 1} {
                set ik [expr {$i+$k}]
                foreach l {-1 0 1} {
                    lappend pixels [lindex $data $ik [expr {$j+$l}]]
                }
            }
            set pix [lindex [lsort -integer $pixels] 4]
            if {$pix != [lindex $data $i $j]} {
                $res put [format \#%02x%02x%02x $pix $pix $pix] -to $j $i
            }
        }
    }
    set res
 }Note also Median Filtering in Constant Time
 based on tracking partial histograms, and similar code on RosettaCode
 based on tracking partial histograms, and similar code on RosettaCode .
.See Arts and crafts of Tcl-Tk programming

