Rent-a-founder

Convert an Image to Grayscale in 2 Lines of Golang

If you turn to Google on how to convert an image (e.g. a JPEG) to grayscale, almost all solutions you will find will cycle through all pixels individually to convert them to a luminance value:

result := image.NewGray(img.Bounds())
for y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {
	for x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {
		result.Set(x, y, img.At(x, y))
	}
}

It seems to me that everybody just copies this solution although you can actually do it in two lines of code with no external libraries:

result := image.NewGray(img.Bounds())
draw.Draw(result, result.Bounds(), img, img.Bounds().Min, draw.Src)

This uses the standard library package "image/draw" and the result will be exactly the same. A colour value in the original image will be converted to RGBA first and then converted to a luminance value as follows, which is a common way to do it:

Y = 0.299R + 0.587G + 0.114B

If you want to use a different formula to convert a colour to grayscale, then of course you will have to revert to the pixel-by-pixel method. For everything else, simplicity is preferable.