histogram.go 833 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package imaging
  2. import (
  3. "image"
  4. )
  5. // Histogram returns a normalized histogram of an image.
  6. //
  7. // Resulting histogram is represented as an array of 256 floats, where
  8. // histogram[i] is a probability of a pixel being of a particular luminance i.
  9. func Histogram(img image.Image) [256]float64 {
  10. src := toNRGBA(img)
  11. width := src.Bounds().Max.X
  12. height := src.Bounds().Max.Y
  13. var histogram [256]float64
  14. var total float64
  15. if width == 0 || height == 0 {
  16. return histogram
  17. }
  18. for y := 0; y < height; y++ {
  19. for x := 0; x < width; x++ {
  20. i := y*src.Stride + x*4
  21. r := src.Pix[i+0]
  22. g := src.Pix[i+1]
  23. b := src.Pix[i+2]
  24. y := 0.299*float32(r) + 0.587*float32(g) + 0.114*float32(b)
  25. histogram[int(y+0.5)]++
  26. total++
  27. }
  28. }
  29. for i := 0; i < 256; i++ {
  30. histogram[i] = histogram[i] / total
  31. }
  32. return histogram
  33. }