import { Color } from './color' ; import { linearRegression , Regression } from './linearRegression' ; import { clamp } from './util' ; export function fitGradient ( image ) { const w = image . width ; const h = image . height ; const d = image . data ; const colors = [ [ ] , [ ] , [ ] ] ; const y = [ ] ; for ( let iy = 0 ; iy < h ; iy ++ ) { for ( let ix = 0 ; ix < w ; ix ++ ) { const i = ( iy * w + ix ) * 4 ; colors [ 0 ] . push ( ( d [ i ] ) ) ; colors [ 1 ] . push ( ( d [ i + 1 ] ) ) ; colors [ 2 ] . push ( ( d [ i + 2 ] ) ) ; y . push ( iy / h ) ; } } const regression = [ linearRegression ( y , colors [ 0 ] ) , linearRegression ( y , colors [ 1 ] ) , linearRegression ( y , colors [ 2 ] ) , ] ; const start = sampleColor ( regression , 0 ) ; const end = sampleColor ( regression , 1 ) ; return [ start , end ] ; } function sampleColor ( regression , t ) { return regression . map ( ( r ) => ( clamp ( r . intercept + r . slope * t , 0 , 255 ) ) | 0 ) as Color ; } type ColorRegression = [ Regression , Regression , Regression ] ;