gray.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2012 Harry de Boer. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ocr
  5. import (
  6. "image"
  7. "image/color"
  8. "math"
  9. )
  10. type ConvertFunc func(color.Color) color.Gray
  11. // Convert converts a color image to grayscale using the provided conversion function.
  12. func Gray(m image.Image, convertColor ConvertFunc) *image.Gray {
  13. b := m.Bounds()
  14. gray := image.NewGray(b)
  15. pos := 0
  16. for y := b.Min.Y; y < b.Max.Y; y++ {
  17. for x := b.Min.X; x < b.Max.X; x++ {
  18. gray.Pix[pos] = convertColor(m.At(x, y)).Y
  19. pos++
  20. }
  21. }
  22. return gray
  23. }
  24. // ToGrayLuminance converts color.Color c to grayscale using Rec 709.
  25. //
  26. // The formula used for conversion is: Y' = 0.2125*R' + 0.7154*G' + 0.0721*B'
  27. // where r, g and b are gamma expanded with gamma 2.2 and final Y is Y'
  28. // gamma compressed again.
  29. // The same formula is used by color.GrayModel.Convert().
  30. func ToGrayLuminance(c color.Color) color.Gray {
  31. rr, gg, bb, _ := c.RGBA()
  32. r := math.Pow(float64(rr), 2.2)
  33. g := math.Pow(float64(gg), 2.2)
  34. b := math.Pow(float64(bb), 2.2)
  35. y := math.Pow(0.2125*r+0.7154*g+0.0721*b, 1/2.2)
  36. Y := uint16(y + 0.5)
  37. return color.Gray{uint8(Y >> 8)}
  38. }