Reputation: 1131
I would like to convert a pixel value to its average greyscale value. The R,G,B components are 1 byte integers (0-255). Is there a way to calculate the average of the pixels (R+G+B)/3 without casting the components to another type?
I would also like to avoid (R/3 + G/3 + B/3) because of edge cases like (2,2,2) which will become 0 instead of 2.
Upvotes: 0
Views: 62
Reputation: 80187
div
is integer division (//
in some languages), mod
is modulo operation (%
in some languages)
Rd = R div 3
Rm = R mod 3
Gd = G div 3
Gm = G mod 3
Bd = B div 3
Bm = B mod 3
Average = Rd + Gd + Bd + (Rm + Gm + Bm) div 3
Upvotes: 1