Created
September 23, 2016 16:42
-
-
Save fogleman/040b248240ca619c71f685667cfd9b5c to your computer and use it in GitHub Desktop.
Dominant Image Color
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dominant | |
import ( | |
"fmt" | |
"image" | |
"image/color" | |
"github.com/mdesenfants/gokmeans" | |
"github.com/nfnt/resize" | |
) | |
func DominantImageColor(im image.Image, k int) color.NRGBA { | |
im = resize.Thumbnail(64, 64, im, resize.Bilinear) | |
rgba := imageToRGBA(im) | |
size := rgba.Bounds().Size() | |
w, h := size.X, size.Y | |
var nodes []gokmeans.Node | |
for y := 0; y < h; y++ { | |
for x := 0; x < w; x++ { | |
c := rgba.RGBAAt(x, y) | |
node := gokmeans.Node{float64(c.R), float64(c.G), float64(c.B)} | |
nodes = append(nodes, node) | |
} | |
} | |
ok, centroids := gokmeans.Train(nodes, k, 100) | |
if !ok { | |
return color.NRGBA{0, 0, 0, 255} | |
} | |
counts := make([]int, k) | |
for _, node := range nodes { | |
index := gokmeans.Nearest(node, centroids) | |
counts[index]++ | |
} | |
for i, centroid := range centroids { | |
fmt.Println(centroid, counts[i]) | |
} | |
bestIndex := 0 | |
bestCount := counts[0] | |
for i, count := range counts { | |
if count > bestCount { | |
bestIndex = i | |
bestCount = count | |
} | |
} | |
centroid := centroids[bestIndex] | |
r := uint8(centroid[0]) | |
g := uint8(centroid[1]) | |
b := uint8(centroid[2]) | |
return color.NRGBA{r, g, b, 255} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment