Updated 2010-10-06 18:36:34 by AKgnome

Richard Suchenwirth 2003-07-28 - A median is the value at the center of a sorted list of values. Here I use the median of a pixel and its eight neighbors to smoothen a photo image obtained by graylevel subsampling, in order to remove the gray-dither effect seen on the original. However, the result is not as good as expected:

Before: After:
 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.

See Arts and crafts of Tcl-Tk programming