Skip to content

Instantly share code, notes, and snippets.

@brooksandrew
Created April 12, 2016 16:52
Show Gist options
  • Save brooksandrew/c9c3ab6ba93ea03fb3fa1ecccef2607a to your computer and use it in GitHub Desktop.
Save brooksandrew/c9c3ab6ba93ea03fb3fa1ecccef2607a to your computer and use it in GitHub Desktop.
Example of color to grayscale conversion with ImageIO in Scala.
import java.io.File
import javax.imageio.ImageIO
import java.awt.Color
object makegray extends App {
def pixels2gray(red: Int, green: Int, blue: Int): Int = (red + green + blue) / 3
def makeGray(img: java.awt.image.BufferedImage): java.awt.image.BufferedImage = {
val w = img.getWidth
val h = img.getHeight
for { w1 <- (0 until w).toVector
h1 <- (0 until h).toVector
} yield {
val col = img.getRGB(w1, h1)
val red = (col & 0xff0000) / 65536
val green = (col & 0xff00) / 256
val blue = (col & 0xff)
val graycol = pixels2gray(red, green, blue)
img.setRGB(w1, h1, new Color(graycol, graycol, graycol).getRGB)
}
img
}
val myimg = ImageIO.read(new File("data/images/train/20.jpg"))
val myimgGray = makeGray(myimg)
ImageIO.write(myimgGray, "jpg", new File("20gray.jpg"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment