2021-09-18

OpenCV kmeans

k-means clustering (維基百科)


我的問題是要怎麼確認我新加到 tcl-opencv 的 kmeans command 是不是有加正確,所以寫了一個簡單的測試程式來測試:

package require opencv

set k [expr 1 + int(5 * rand())]
set samplecount [expr 500 + int(500 * rand())]

set colors [list [list 255 0 0 0] [list 0 0 255 0] \
                 [list 0 255 0 0] [list 0 165 255 0] \
                 [list 255 165 0 0] [list 255 255 255 0]]

set image [::cv::Mat::Mat 512 512 $::cv::CV_8UC3]
set term [::cv::TermCriteria [expr $::cv::EPS | $::cv::COUNT] 10 1]

while {1} {
    $image setTo [list 0 0 0 0]
    set points [cv::Mat::Mat $samplecount 1 $::cv::CV_32FC2]
    cv::randu $points [list 0 0 0 0] [list 512 512 0 0]

    set result [cv::kmeans $points $k None $term 3 $::cv::KMEANS_PP_CENTERS]
    puts "K = $k, compactness: [lindex $result 0]"

    set labels [lindex $result 1]
    for {set i 0} {$i < [$points rows]} {incr i} {
        set x [expr int([$points at [list $i 0] 0])]
        set y [expr int([$points at [list $i 0] 1])]

        set color [lindex $colors [expr int([$labels at [list $i 0] 0])]]
        cv::circle $image $x $y 2 $color 1 $cv::LINE_AA 0
    }

    set output [lindex $result 2]
    for {set i 0} {$i < [$output rows]} {incr i} {
        set x [expr int([$output at [list $i 0] 0])]
        set y [expr int([$output at [list $i 1] 0])]
        set color [lindex $colors $i]
        cv::circle $image $x $y 40 $color 1 $cv::LINE_AA 0
    }

    ::cv::imshow "Result" $image

    $labels close
    $points close
    
    set key [::cv::waitKey 0]
    if {$key==[scan "q" %c] || $key == 27} {
        break
    } else {
        set k [expr 2 + int(3 * rand())]
        set samplecount [expr 200 + int(1000 * rand())]
    }
}

$image close
$term close

沒有留言: