/** * Returns the image that is generated from the given disjoint set. * If the randomColors parameter is true, a random color will be assigned * to each segment of the image. If it's false, then the mean color of * the pixels in the original image will be assigned to each segment. */ func imageFromDisjointSet(set *disjointset.DisjointSet, originalimg image.Image, randomColors bool) image.Image { resultimg := image.NewNRGBA(originalimg.Bounds()) width := originalimg.Bounds().Max.X height := originalimg.Bounds().Max.Y meanColors := make([]ImageColor, width*height, width*height) if randomColors { for u := 0; u < width*height; u++ { meanColors[u] = randomColor() } } else { for y := 0; y < height; y++ { for x := 0; x < width; x++ { c := set.Find(x + y*width) r, g, b, _ := originalimg.At(x, y).RGBA() meanColors[c].r += float32(r>>8) / float32(set.Size(c)) meanColors[c].g += float32(g>>8) / float32(set.Size(c)) meanColors[c].b += float32(b>>8) / float32(set.Size(c)) } } } for x := 0; x < width; x++ { for y := 0; y < height; y++ { resultimg.Set(x, y, &meanColors[set.Find(x+y*width)]) } } return resultimg }
/** * Computes the threshold used by the GBS algorithm. * T(c) = k/|c| */ func threshold(set *disjointset.DisjointSet, k float64, u int) float64 { return k / float64(set.Size(u)) }