【问题标题】:How to count green pixel in an image using Scala map reduce如何使用Scala map reduce计算图像中的绿色像素
【发布时间】:2017-12-05 06:33:41
【问题描述】:

我是 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 算法计算绿色像素的数量?

【问题讨论】:

  • isBetween 中的最后两个比较与前四个不一致。另外,您是指 Hadoop 中的 MapReduce 还是标准的 mapreduce 函数?

标签: image scala mapreduce


【解决方案1】:

你可以改写如下:

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
}

【讨论】:

  • 非常感谢 KyBe。会试试这个......如果你分享你的电子邮件ID会很有帮助。
猜你喜欢
  • 2023-04-08
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 2011-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多