# Apply a sepia filter to an image

I'm writing a simple function that applies a Sepia filter to an image. My function works, but I'm a beginner gopher. So I would like to know if there is a way to improve the code. I usually code in Javascript, so I have troubles with a strong typed language such as go.

// Sepia apply a sepia filter to Image.
func Sepia(pic image.Image) (output *image.RGBA) {

bounds := pic.Bounds()
w, h := bounds.Max.X, bounds.Max.Y
rect := image.Rect(0, 0, w, h)
output = image.NewRGBA(rect)

for x := bounds.Min.X; x <= w; x++ {
for y := bounds.Min.Y; y <= h; y++ {
r, g, b, a := pic.At(x, y).RGBA()
// Part to improve from HERE
r >>= 8
g >>= 8
b >>= 8
a >>= 8

r = uint32(math.Min(.393*float64(r)+.769*float64(g)+.189*float64(b), 255))
g = uint32(math.Min(.349*float64(r)+.686*float64(g)+.168*float64(b), 255))
b = uint32(math.Min(.272*float64(r)+.534*float64(g)+.131*float64(b), 255))

newColor := color.RGBA{
uint8(r),
uint8(g),
uint8(b),
uint8(a),
}
// to HERE
output.Set(x, y, newColor)
}
}
return
}


## migrated from stackoverflow.comAug 12 at 0:10

This question came from our site for professional and enthusiast programmers.

I would like to know if there is a way to improve the code.

// Part to improve from HERE
r >>= 8
g >>= 8
b >>= 8
a >>= 8

r = uint32(math.Min(.393*float64(r)+.769*float64(g)+.189*float64(b), 255))
g = uint32(math.Min(.349*float64(r)+.686*float64(g)+.168*float64(b), 255))
b = uint32(math.Min(.272*float64(r)+.534*float64(g)+.131*float64(b), 255))

newColor := color.RGBA{
uint8(r),
uint8(g),
uint8(b),
uint8(a),
}
// to HERE


In Go, readability is paramount. I would write:

// Part to improve from HERE

rr := float64(r >> 8)
gg := float64(g >> 8)
bb := float64(b >> 8)
aa := a >> 8

newColor := color.RGBA{
R: uint8(math.Min(.393*rr+.769*gg+.189*bb, 255)),
G: uint8(math.Min(.349*rr+.686*gg+.168*bb, 255)),
B: uint8(math.Min(.272*rr+.534*gg+.131*bb, 255)),
A: uint8(aa),
}

// to HERE

• Thanks you it look cleaner ! – Nergel Aug 12 at 11:22