Skip to content

Instantly share code, notes, and snippets.

@brydavis
Created November 5, 2018 08:07
Show Gist options
  • Save brydavis/63507c5f0e0325469bd36aa91cdedfcd to your computer and use it in GitHub Desktop.
Save brydavis/63507c5f0e0325469bd36aa91cdedfcd to your computer and use it in GitHub Desktop.
extracting color samples from a picture of a big pumpkin
// https://www.devdungeon.com/content/working-images-go#reading_image_from_file
// https://socketloop.com/tutorials/golang-get-rgba-values-of-each-image-pixel
package main
import (
"fmt"
"image"
"image/jpeg"
"os"
"sort"
"strconv"
"strings"
)
var colorMap = map[string]bool{}
func init() {
// damn important or else At(), Bounds() functions will
// caused memory pointer error!!
image.RegisterFormat("jpeg", "jpeg", jpeg.Decode, jpeg.DecodeConfig)
}
func main() {
imgfile, err := os.Open("path/to/pics/pumpkin.jpg")
if err != nil {
fmt.Println("img.jpg file not found!")
os.Exit(1)
}
defer imgfile.Close()
out, _ := os.Create("image_analysis.html")
// l := log.New(out, "", 0777)
fmt.Fprintln(out, "<style>div{height:50px;width:200px}</style>")
// get image height and width with image/jpeg
// change accordinly if file is png or gif
imgCfg, _, err := image.DecodeConfig(imgfile)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sampleSize := 0.5
width := imgCfg.Width
height := imgCfg.Height
fmt.Println("Width : ", width)
fmt.Println("Height : ", height)
// we need to reset the io.Reader again for image.Decode() function below to work
// otherwise we will - panic: runtime error: invalid memory address or nil pointer dereference
// there is no build in rewind for io.Reader, use Seek(0,0)
imgfile.Seek(0, 0)
// get the image
img, _, err := image.Decode(imgfile)
fmt.Println(img.At(10, 10).RGBA())
// for y := 0; y < height ; y++ {
for y := 0; y < int(float64(height)*sampleSize); y++ {
for x := 0; x < int(float64(width)*sampleSize); x++ {
r, g, b, a := img.At(x, y).RGBA()
R := r >> 8
G := g >> 8
B := b >> 8
A := a >> 8
colorMap[fmt.Sprintf("%v:%v:%v:%v", R, G, B, A)] = true
}
}
// To store the keys in slice in sorted order
var keys []string
for k := range colorMap {
keys = append(keys, k)
}
sort.Strings(keys)
for _, c := range keys {
split := strings.Split(c, ":")
R, G, B, A := split[0], split[1], split[2], split[3]
i, _ := strconv.Atoi(R)
if i >= 200 {
fmt.Fprintf(out, "<div style=\"background-color: rgba(%v, %v, %v, %v)\">rgba(%v, %v, %v, %v)</div>", R, G, B, A, R, G, B, A)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment