我正在尝试计算
Scala中图像的平均颜色,其中“average”被定义为redSum / numpixels,greenSum / numpixels,blueSum / numpixels.
以下是我用来计算图像矩形区域(光栅)的平均颜色的代码.
// 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,a1,... 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) }
在不同的交错阵列上总结了一个比较惯用的Scala方法吗?一些方法可以在每个第四个元素上迭代数组的投影?我对Stack Overflow社区可以提供的任何专业知识感兴趣.
解决方法
pixel.grouped(3)将返回一个3元素数组的Iterator [Array [Int]].所以
val pixelRGBs = pixels.grouped(3) val (redSum,greenSum,blueSum) = pixelRGBs.foldLeft((0,0)) {case ((rSum,gSum,bSum),Array(r,g,b)) => (rSum + r,gSum + g,bSum + b)} new Color(redSum / numPixels,blueSum / numPixels)
更新:要处理3和4通道,我会写
pixels.grouped(numChannels).foldLeft((0,b,_*)) => (rSum + r,bSum + b)}
_ *这里基本上是指“0或更多元素”.请参阅http://programming-scala.labs.oreilly.com/ch03.html中的“序列匹配”