我是Scala编程的新手,我正在尝试使用Scala(特别是绿色)计算图像中的RGB值。以下是仅计算绿色像素的代码。我的问题是,如何使用Scala map reduce算法实现相同的效果?
....
val lightGreen = new Color(0,255,0)
val darkGreen = new Color(0,100,0)
var ctrGreen = 0
var ctrTotal = 0
for (x <- 0 until w)
for (y <- 0 until h) {
val c = new Color(img.getRGB(x, y))
if (isBetween(c, lightGreen,darkGreen)) {
ctrGreen += 1
}
ctrTotal += 1;
}
println("Green pixel count: " + ctrGreen)
println("Total pixel count: " + ctrTotal)
def isBetween(c: Color, c1: Color, c2: Color): Boolean = {
c.getRed >= c1.getRed && c.getRed <= c2.getRed &&
c.getBlue >= c1.getBlue && c.getBlue <= c2.getBlue &&
c.getGreen <= c1.getGreen && c.getGreen >= c2.getGreen
}
如何使用Scala中的map reduce算法计算绿色像素的数量?
答案 0 :(得分:0)
您可以按以下方式重写:
val rangeX = (0 until w)
val rangeY = (0 until h)
val (greenPixels, allPixels) = (for ( x <- rangeX; y <- rangeY ) yield( (isGreen(x, y), 1) )).reduce( (a, b) => (a._1 + b._1, a._2 + b._2) )
或者采用更具功能性的方法:
val (greenPixels, allPixels) = rangeX.flatMap( x => rangeY.map( y => (isGreen(x, y), 1) ) )
.reduce( (a, b) => (a._1 + b._1, a._2 + b._2) )
格林在哪里
def isGreen(x: Int, y: Int) =
{
val c = new Color(img.getRGB(x, y))
val isGreenAsInt = if( isBetween(c, lightGreen,darkGreen) ) 1 else 0
isGreenAsInt
}