blur.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright 2011 The Graphics-Go Authors. 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 graphics
  5. import (
  6. "code.google.com/p/graphics-go/graphics/convolve"
  7. "errors"
  8. "image"
  9. "image/draw"
  10. "math"
  11. )
  12. // DefaultStdDev is the default blurring parameter.
  13. var DefaultStdDev = 0.5
  14. // BlurOptions are the blurring parameters.
  15. // StdDev is the standard deviation of the normal, higher is blurrier.
  16. // Size is the size of the kernel. If zero, it is set to Ceil(6 * StdDev).
  17. type BlurOptions struct {
  18. StdDev float64
  19. Size int
  20. }
  21. // Blur produces a blurred version of the image, using a Gaussian blur.
  22. func Blur(dst draw.Image, src image.Image, opt *BlurOptions) error {
  23. if dst == nil {
  24. return errors.New("graphics: dst is nil")
  25. }
  26. if src == nil {
  27. return errors.New("graphics: src is nil")
  28. }
  29. sd := DefaultStdDev
  30. size := 0
  31. if opt != nil {
  32. sd = opt.StdDev
  33. size = opt.Size
  34. }
  35. if size < 1 {
  36. size = int(math.Ceil(sd * 6))
  37. }
  38. kernel := make([]float64, 2*size+1)
  39. for i := 0; i <= size; i++ {
  40. x := float64(i) / sd
  41. x = math.Pow(1/math.SqrtE, x*x)
  42. kernel[size-i] = x
  43. kernel[size+i] = x
  44. }
  45. // Normalize the weights to sum to 1.0.
  46. kSum := 0.0
  47. for _, k := range kernel {
  48. kSum += k
  49. }
  50. for i, k := range kernel {
  51. kernel[i] = k / kSum
  52. }
  53. return convolve.Convolve(dst, src, &convolve.SeparableKernel{
  54. X: kernel,
  55. Y: kernel,
  56. })
  57. }