@@ -148,16 +148,41 @@ function pointDansPolygone(px, py, sommets) {
148148 return dedans ;
149149}
150150
151- function couleurImageKMeans ( pixels , larg , haut , maxSamples = 96 ) {
151+ function couleurImageMoyenne ( pixels , larg , haut , maxSamples = 96 ) {
152152 const total = larg * haut ;
153+ if ( total <= 0 ) return [ 0 , 0 , 0 ] ;
153154 const step = Math . max ( 1 , Math . floor ( total / maxSamples ) ) ;
154- km_init ( 3 ) ;
155+ let rTot = 0 , gTot = 0 , bTot = 0 , compte = 0 ;
155156 for ( let i = 0 ; i < total ; i += step ) {
156157 const idx = i * 4 ;
157- km_ajouter ( pixels [ idx ] , pixels [ idx + 1 ] , pixels [ idx + 2 ] ) ;
158+ rTot += pixels [ idx ] ;
159+ gTot += pixels [ idx + 1 ] ;
160+ bTot += pixels [ idx + 2 ] ;
161+ compte ++ ;
162+ }
163+ if ( compte === 0 ) return [ 0 , 0 , 0 ] ;
164+ return [
165+ couleur_moyenne ( rTot , compte ) ,
166+ couleur_moyenne ( gTot , compte ) ,
167+ couleur_moyenne ( bTot , compte ) ,
168+ ] ;
169+ }
170+
171+ function couleurImageKMeans ( pixels , larg , haut , maxSamples = 96 ) {
172+ try {
173+ const total = larg * haut ;
174+ const step = Math . max ( 1 , Math . floor ( total / maxSamples ) ) ;
175+ km_init ( 3 ) ;
176+ for ( let i = 0 ; i < total ; i += step ) {
177+ const idx = i * 4 ;
178+ km_ajouter ( pixels [ idx ] , pixels [ idx + 1 ] , pixels [ idx + 2 ] ) ;
179+ }
180+ km_calculer ( 20 ) ;
181+ return km_resultat ( ) ;
182+ } catch ( err ) {
183+ console . warn ( "[pixel2polygon] K-means indisponible, repli sur la moyenne :" , err ) ;
184+ return couleurImageMoyenne ( pixels , larg , haut , maxSamples ) ;
158185 }
159- km_calculer ( 20 ) ;
160- return km_resultat ( ) ;
161186}
162187
163188function couleurTuile ( pixels , larg , haut , sommets ) {
0 commit comments