Given an array of RGB{UInt8} values, how can we collect the sums of their independent :r, :g, and :b 8-bit components, without overflowing?
We can write a for loop and do this manually:
for v in arr
r += v.r
g += v.g
b += v.b
end
We can use the sum function:
r = sum(v -> v.r, arr)
g = sum(v -> v.g, arr)
b = sum(v -> v.b, arr)
but this is likely to be much less efficient than the for loop, because it has to iterate three times, correct?
If we write:
rgbsum = sum(arr)
we overflow if arr is an array of RGB structs with 8-bit fields.
Is there a way to ask the sum function to accumulate its sum into an RGB{Float64}, for example, so that rgbsum = sum(arr) would work without overflow and as efficiently as the explicit for loop?
I’m sorry for the type confusion. This RGB type comes from the Images package, but I was intending to ask a more general question, which you’ve both answered.
I like the typecast approach of sum(RGB{Float64}, arr), but it seems to perform much worse than the foldl(+, arr, init=RGB{Float64}(0,0,0)) approach. 20ms vs 0.25ms for an array of size (460, 374).
That’s worth raising as an issue, unless the difference is compilation time or something like that. Could you please post a complete example, either here or on Github, with the code you ran that printed those times?