如何在scala中将图像(.jpg)转换为数组,以及如何使用scala

时间:2017-11-09 05:13:03

标签: scala

import java.io.File
import javax.imageio.ImageIO
import java.awt.image.BufferedImage

val img = ImageIO.read(newFile("Filename.jpg"))

val w = img.getWidth
val h = img.getHeight

for (x <- 0 until w)
  for (y <- 0 until h)
     img.getRGB(x,y)

ImageIO.write(img,"jpg",new File("test.jpg"))

如何将img转换为字节数组并计算相同的绿色像素。

1 个答案:

答案 0 :(得分:0)

您可以通过将每个像素的RGB值与绿色的RGB值进行比较来计算绿色像素。 例如:

    ...
    val w = img.getWidth
    val h = img.getHeight

    val green = Color.GREEN

    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 (isEqual(c, green)) {
          ctrGreen += 1
        }
        ctrTotal += 1;
      }

    println("Green pixel count: " + ctrGreen)
    println("Total pixel count: " + ctrTotal)
  }

  def isEqual(c1: Color, c2: Color): Boolean = {
    c1.getRed == c2.getRed && c1.getBlue == c2.getBlue && c1.getGreen == c2.getGreen
  }

但有时候很难找到颜色RGB值的精确匹配(即绿色情况下是(0,255,0))。因此,您还可以检查像素是否属于颜色范围。示例:

    ....
    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
  }