Skip to content

Instantly share code, notes, and snippets.

@preslavrachev
Last active January 2, 2021 07:30
Show Gist options
  • Save preslavrachev/072303c9de3790d4e995ba39bf99a789 to your computer and use it in GitHub Desktop.
Save preslavrachev/072303c9de3790d4e995ba39bf99a789 to your computer and use it in GitHub Desktop.
A Simple Grayscale Filter in Golang

This is a simple grayscale filter implementening image.Image. It can be used in place where an image.Image is expected.

img, err := loadImage("input.jpg")
// check error

err := saveImage(&GrayscaleFilter{img})
//check error

The approach above uses the so-called "luminosity method" for averaging colors


P.S. Learn more about this and other Graphics Programming stuff in Go in my book Generative Art in Go.

type GrayscaleFilter struct {
image.Image
}
func (f *GrayscaleFilter) At(x, y int) color.Color {
r, g, b, a := f.Image.At(x, y).RGBA()
grey := uint16(float64(r)*0.21 + float64(g)*0.72 + float64(b)*0.07)
return color.RGBA64{
R: grey,
G: grey,
B: grey,
A: uint16(a),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment