Hi all,
I'm attempting to calculate the average color of an image in Scala, where "average" is defined as the redSum/numpixels, greenSum/numpixels, blueSum/numpixels .
Here is the code I am using to calculate the average color in a rectangular region of an image (the Raster).
// A raster is an abstraction of a piece of an image and the underlying
// pixel data.
// For instance, we can get a raster than is of the upper left twenty
// pixel square of an image
def calculateColorFromRaster(raster:Raster): Color = {
var redSum = 0
var greenSum = 0
var blueSum = 0
val minX = raster.getMinX()
val minY = raster.getMinY()
val height = raster.getHeight()
val width = raster.getWidth()
val numPixels = height * width
val numChannels = raster.getNumBands()
val pixelBuffer = new Array[Int](width*height*numChannels)
val pixels = raster.getPixels(minX,minY,width,height,pixelBuffer)
// pixelBuffer now filled with r1,g1,b1,r2,g2,b2,...
// If there's an alpha channel, it will be r1,g1,b1,a1,r2,... but we skip the alpha
for (i <- 0 until numPixels) {
val redOffset = numChannels * i
val red = pixels(redOffset)
val green = pixels(redOffset+1)
val blue = pixels(redOffset+2)
redSum+=red
greenSum+=green
blueSum+=blue
}
new Color(redSum / numPixels, greenSum / numPixels, blueSum / numPixels)
}
Is there a more idiomatic Scala way of summing up over the different interleaved arrays? Some way to get a projection over the array that iterates over every 4th element? I'm interested in any expertise the Stack Overflow community can provide.