@@ -268,20 +268,32 @@ func TestTakecolor_SolidColorKGreaterThan1(t *testing.T) {
268268}
269269
270270func TestTakecolor_TwoDistinctColors (t * testing.T ) {
271- // k-means 的初始中心随机选取,可能两次都落到同一颜色区域导致不收敛。
272- // 多次运行,验证算法至少能在 30 次尝试中有一次正确分离两种颜色。
271+ // 用偏离正确答案的初始中心,验证 k-means 能通过迭代收敛并正确分离两种颜色。
273272 img := twoColorImage (20 , 20 , Red , Blue )
274- const maxAttempts = 30
275- for range maxAttempts {
276- result , err := TakeThemeColorsKMeans (img , 2 )
277- if err != nil {
273+ ki , err := newKMeansImage (img , 2 )
274+ if err != nil {
275+ t .Fatal (err )
276+ }
277+ defer ki .destroy ()
278+ // 初始中心偏离真实颜色,迫使算法迭代收敛
279+ ki .clusters [0 ] = color.RGBA {200 , 50 , 50 , 255 } // 偏红
280+ ki .clusters [1 ] = color.RGBA {50 , 50 , 200 , 255 } // 偏蓝
281+ for {
282+ if err := ki .assign (); err != nil {
278283 t .Fatal (err )
279284 }
280- if len (result ) == 2 && colorInSlice (Red , result , 5 ) && colorInSlice (Blue , result , 5 ) {
281- return // 成功分离,测试通过
285+ ki .update ()
286+ if ki .epilogue () {
287+ break
282288 }
283289 }
284- t .Errorf ("takecolor failed to separate red and blue colors in %d attempts" , maxAttempts )
290+ result := ki .result ()
291+ if len (result ) != 2 {
292+ t .Fatalf ("expected 2 colors, got %d" , len (result ))
293+ }
294+ if ! colorInSlice (Red , result , 5 ) || ! colorInSlice (Blue , result , 5 ) {
295+ t .Errorf ("k-means failed to separate red and blue: got %v" , result )
296+ }
285297}
286298
287299func TestTakecolor_Deterministic_SolidImage (t * testing.T ) {
0 commit comments