Calculating the average of several Color3s

How would I go on writing a function that, where you put in Color3s as variadic arguments, will return the average of it?

use a loop to sum each of r, g, and b and divide by the total number of values.

-- RGB (naive):
function getAverageColorRGB(colors)
	local r,g,b = 0,0,0
	for _,c in pairs(colors) do
		r = r + c.r
		g = g + c.g
		b = b + c.b
	end
	return Color3.new(r/#colors, g/#colors, b/#colors)
end

-- HSV space:
function getAverageColorHSV(colors)
	local h,s,v = 0,0,0
	for _,c in pairs(colors) do
		local ch, cs, cv = Color3.toHSV(c)
		h = h + ch
		s = s + cs
		v = v + cv
	end
	return Color3.fromHSV(h/#colors, s/#colors, v/#colors)
end
4 Likes