javax.imageio.ImageIO Scala Examples

The following examples show how to use javax.imageio.ImageIO. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Util.scala    From Machine-Learning-with-Spark-Second-Edition   with MIT License 5 votes vote down vote up
package org.sparksamples

import java.awt.image.BufferedImage


object Util {
  def loadImageFromFile(path: String): BufferedImage = {
    import javax.imageio.ImageIO
    import java.io.File
    ImageIO.read(new File(path))
  }

  def processImage(image: BufferedImage, width: Int, height: Int): BufferedImage = {
    val bwImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY)
    val g = bwImage.getGraphics()
    g.drawImage(image, 0, 0, width, height, null)
    g.dispose()
    bwImage
  }

  def getPixelsFromImage(image: BufferedImage): Array[Double] = {
    val width = image.getWidth
    val height = image.getHeight
    val pixels = Array.ofDim[Double](width * height)
    image.getData.getPixels(0, 0, width, height, pixels)
    // pixels.map(p => p / 255.0) 		// optionally scale to [0, 1] domain
  }

  def extractPixels(path: String, width: Int, height: Int): Array[Double] = {
    val raw = loadImageFromFile(path)
    val processed = processImage(raw, width, height)
    getPixelsFromImage(processed)
  }


} 
Example 2
Source File: Bencharts.scala    From rtree2d   with Apache License 2.0 5 votes vote down vote up
import java.awt.{Color, Paint}
import java.text.NumberFormat

import javax.imageio.ImageIO
import org.jfree.chart.JFreeChart
import org.jfree.chart.axis.LogarithmicAxis
import org.jfree.chart.plot.{DefaultDrawingSupplier, XYPlot}
import org.jfree.chart.renderer.xy.XYErrorRenderer
import org.jfree.data.xy.{YIntervalSeries, YIntervalSeriesCollection}
import sbt._
import com.github.plokhotnyuk.jsoniter_scala.macros._
import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker._

import scala.collection.SortedMap


  def apply(jmhReport: File, yAxisTitle: String, targetDir: File): Unit = {
    val allResults = readFromArray(IO.readBytes(jmhReport))(make[Seq[BenchmarkResult]](CodecMakerConfig))
    val constParams = allResults.flatMap(_.params.toSeq).groupBy(_._1).collect {
      case (_, kvs) if kvs.distinct.size == 1 => kvs.head
    }.toSeq
    allResults.groupBy(benchmarkName(constParams)).foreach { case (benchmark, results) =>
      val dataset = new YIntervalSeriesCollection {
        SortedMap(results.groupBy(otherParams(constParams)).toSeq:_*).foreach { case (params, iterations) =>
          addSeries(new YIntervalSeries(params) {
            iterations.foreach { iteration =>
              val x = iteration.params.get("size").fold(0.0)(_.toDouble)
              val y = Math.max(iteration.primaryMetric.score, 1.0)
              val yLow = Math.max(iteration.primaryMetric.scoreConfidence._1, 1.0)
              val yHigh = Math.max(iteration.primaryMetric.scoreConfidence._2, 1.0)
              add(x, y, yLow, yHigh)
            }
          })
        }
      }
      val renderer = new XYErrorRenderer {
        (0 to dataset.getSeriesCount).foreach(i => setSeriesLinesVisible(i, true))
      }
      val plot = new XYPlot(dataset, axis("Size"), axis(yAxisTitle), renderer) {
        setDrawingSupplier(new DefaultDrawingSupplier {
          override def getNextPaint: Paint = super.getNextPaint match {
            case x: Color if x.getRed > 200 && x.getGreen > 200 =>
              new Color(x.getRed, (x.getGreen * 0.8).toInt, x.getBlue, x.getAlpha)
            case x => x
          }
        })
      }
      val chart = new JFreeChart(benchmark, JFreeChart.DEFAULT_TITLE_FONT, plot, true)
      ImageIO.write(chart.createBufferedImage(1200, 900), "png", targetDir / s"$benchmark.png")
    }
  }

  private def axis(title: String): LogarithmicAxis = new LogarithmicAxis(title) {
    setAllowNegativesFlag(true)
    setNumberFormatOverride(NumberFormat.getInstance())
  }

  private def benchmarkName(constParams: Seq[(String, String)])(result: BenchmarkResult): String = {
    val benchName = result.benchmark.split("""\.""").last
    constParams.map { case (k, v) =>
      s"$k=$v"
    }.sorted.mkString(s"$benchName[", ",", "]")
  }

  private def otherParams(constParams: Seq[(String, String)])(result: BenchmarkResult): String = {
    val constParamNames = constParams.map(_._1).toSet
    val benchSuitName = result.benchmark.split("""\.""").reverse.tail.head
    result.params.filterKeys(k => k != "size" && !constParamNames(k)).map { case (k, v) =>
      s"$k=$v"
    }.toSeq.sorted.mkString(s"$benchSuitName[", ",", "]")
  }
}

case class BenchmarkMetric(score: Double, scoreConfidence: (Double, Double))

case class BenchmarkResult(benchmark: String, params: Map[String, String], primaryMetric: BenchmarkMetric) 
Example 3
Source File: ColorPalette.scala    From shapenet-viewer   with MIT License 5 votes vote down vote up
package edu.stanford.graphics.shapenet.colors

import java.awt.Color
import javax.imageio.ImageIO
import java.io.File

import edu.stanford.graphics.shapenet.Constants


trait ColorPalette {
  def getColor(id: Int): Color
  def getColorCount(): Int = -1

  def getColor(id: Int, alpha: Float): Color = {
    val c = getColor(id)
    edu.stanford.graphics.shapenet.colors.getColor(c, alpha)
  }
}

class ColorBar(rgbColors: Array[Color]) extends ColorPalette {
  val nColors = rgbColors.length
  def getColor(r: Double): Color = getColor((r*(nColors-1)).toInt)
  def getColor(id: Int): Color = rgbColors(id % nColors)
  override def getColorCount() = nColors
}

object ColorBar {
  val texturesDir = Constants.ASSETS_DIR + "Textures" + File.separator
  lazy val coolwarmBar = ColorBar(texturesDir + "Cool2WarmBar.png")
  lazy val warmBar = ColorBar(texturesDir + "heatmap.png")
  def apply(filename: String): ColorBar = {
    val img = ImageIO.read(new File(filename))
    val rgb = Array.ofDim[Color](img.getWidth)
    for (x <- 0 until rgb.length) {
      rgb(x) = new Color(img.getRGB(x, 0))
    }
    new ColorBar(rgb)
  }
}

object PhiColorPalette extends ColorPalette {
  def getColor(id: Int): Color = {
    val startColor = new Color(0x4FD067)
    val hsb = Color.RGBtoHSB(startColor.getRed, startColor.getGreen, startColor.getBlue, null)
    val invPhi = 1.0/Constants.phi
    var hue = hsb(0) + id*invPhi
    hue = hue - math.floor(hue)
    val c = Color.getHSBColor(hue.toFloat, 0.5f, 0.95f)
    // Switch blue and green for nice pretty colors
    new Color(c.getRed, c.getBlue, c.getGreen)
  }
}

object DefaultColorPalette extends ColorPalette {
  def getColor(id: Int): Color = {
    var h = (-3.88 * id) % (2*Math.PI)
    if (h<0) h += 2*Math.PI
    h /= 2*Math.PI
    val c = Color.getHSBColor(h.toFloat, (0.4 + 0.2 * Math.sin(0.42 * id)).toFloat, 0.5f)
    c
  }
} 
Example 4
Source File: BitMap.scala    From Scurses   with MIT License 5 votes vote down vote up
package net.team2xh.onions.components.widgets

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

import net.team2xh.onions.Symbols
import net.team2xh.onions.Themes.ColorScheme
import net.team2xh.onions.components.{FramePanel, Widget}
import net.team2xh.scurses.{Colors, Scurses}

object BitMap {

  def apply(parent: FramePanel, path: String, relative: Boolean = false)(implicit screen: Scurses): BitMap = {
    val fullPath = if (relative) new File("").getAbsolutePath + path else path
    val image = ImageIO.read(new File(fullPath))
    new BitMap(parent, image)
  }

  def apply(parent: FramePanel, image: BufferedImage)(implicit screen: Scurses): BitMap = {
    new BitMap(parent, image)
  }

}

class BitMap(parent: FramePanel, image: BufferedImage)
                 (implicit screen: Scurses) extends Widget(parent) {

  val colors = {
    val width = image.getWidth
    val height = image.getHeight
    for (x <- 0 until width)
      yield for (y <- 0 until height / 2) yield {
        // Read two rows at a time
        val upper = Colors.fromRGBInt(image.getRGB(x, y * 2))
        val lower = if (height % 2 == 1) -1 else Colors.fromRGBInt(image.getRGB(x, y * 2 + 1))
        (upper, lower)
      }
  }

  override def redraw(focus: Boolean, theme: ColorScheme): Unit = {
    val width = image.getWidth min innerWidth
    val x0 = (innerWidth - width) / 2
    for (x <- 0 until width) {
      for (y <- 0 until innerHeight) {
        // Read two rows at a time
        val c = colors(x)(y)
        screen.put(x0 + x, y, Symbols.BLOCK_UPPER, c._1, c._2)
      }
    }
  }

  override def handleKeypress(keypress: Int): Unit = { }

  override def focusable: Boolean = false
  override def innerHeight: Int = image.getHeight / 2
} 
Example 5
Source File: ScaleAndConvert.scala    From SparkNet   with MIT License 5 votes vote down vote up
package preprocessing

import java.awt.image.DataBufferByte
import java.io.ByteArrayInputStream
import javax.imageio.ImageIO

import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConversions._
import net.coobird.thumbnailator._

import org.apache.spark.rdd.RDD

import libs._

object ScaleAndConvert {
  def BufferedImageToByteArray(image: java.awt.image.BufferedImage) : Array[Byte] = {
    val height = image.getHeight()
    val width = image.getWidth()
    val pixels = image.getRGB(0, 0, width, height, null, 0, width)
    val result = new Array[Byte](3 * height * width)
    var row = 0
    while (row < height) {
      var col = 0
      while (col < width) {
        val rgb = pixels(row * width + col)
        result(0 * height * width + row * width + col) = ((rgb >> 16) & 0xFF).toByte
        result(1 * height * width + row * width + col) = ((rgb >> 8) & 0xFF).toByte
        result(2 * height * width + row * width + col) = (rgb & 0xFF).toByte
        col += 1
      }
      row += 1
    }
    result
  }

  def decompressImageAndResize(compressedImage: Array[Byte], height: Int, width: Int) : Option[Array[Byte]] = {
    // this method takes a JPEG, decompresses it, and resizes it
    try {
      val im = ImageIO.read(new ByteArrayInputStream(compressedImage))
      val resizedImage = Thumbnails.of(im).forceSize(width, height).asBufferedImage()
      Some(BufferedImageToByteArray(resizedImage))
    } catch {
      // If images can't be processed properly, just ignore them
      case e: java.lang.IllegalArgumentException => None
      case e: javax.imageio.IIOException => None
      case e: java.lang.NullPointerException => None
    }
  }
} 
Example 6
Source File: SuperpixelSuite.scala    From mmlspark   with MIT License 5 votes vote down vote up
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in project root for information.

package com.microsoft.ml.spark.lime

import java.awt.Color
import java.awt.image.BufferedImage
import java.io.File

import com.microsoft.ml.spark.cntk.CNTKTestUtils
import com.microsoft.ml.spark.io.image.ImageUtils
import javax.imageio.ImageIO

import scala.util.Random

class SuperpixelSuite extends CNTKTestUtils {

  lazy val sp1 = new Superpixel(img, 16, 130)
  lazy val sp2 = new Superpixel(img2, 100, 130)
  lazy val width = 300
  lazy val height = 300
  lazy val rgbArray = new Array[Int](width * height)
  lazy val img: BufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
  lazy val img2: BufferedImage = ImageIO.read(
    new File(s"$filesRoot/Images/Grocery/testImages/WIN_20160803_11_28_42_Pro.jpg"))

  // Adds colors to the img
  for (y <- 0 until height) {
    val red = (y * 255) / (height - 1)
    for (x <- 0 until width) {
      val green = (x * 255) / (width - 1)
      val blue = 128
      rgbArray(x + y * height) = (red << 16) | (green << 8) | blue
    }
  }
  img.setRGB(0, 0, width, height, rgbArray, 0, width)

  lazy val allClusters: Array[Cluster] = sp1.clusters
  lazy val allClusters2: Array[Cluster] = sp2.clusters
  lazy val states: Array[Boolean] = Array.fill(allClusters.length) {
    Random.nextDouble() > 0.5
  }
  lazy val states2: Array[Boolean] = Array.fill(allClusters2.length) {
    Random.nextDouble() > 0.5
  }

  lazy val superpixels: SuperpixelData = SuperpixelData.fromSuperpixel(sp1)
  lazy val superpixels2: SuperpixelData = SuperpixelData.fromSuperpixel(sp2)

  lazy val censoredImg: BufferedImage = Superpixel.maskImage(
    ImageUtils.toSparkImage(img).getStruct(0), superpixels, states)
  lazy val censoredImg2: BufferedImage = Superpixel.maskImage(
    ImageUtils.toSparkImage(img).getStruct(0), superpixels2, states2)

  test("ToList should work on an state sampler") {
    val sampler = LIMEUtils.randomMasks(0.3, 1000)
    val samples: List[Array[Boolean]] = sampler.take(10).toList
    assert(samples.size === 10)
  }

  ignore("GetClusteredImage should show the image with its clusters outlined, not censored") {
    Superpixel.displayImage(sp1.getClusteredImage)
    Superpixel.displayImage(censoredImg)
    Superpixel.displayImage(sp2.getClusteredImage)
    Superpixel.displayImage(censoredImg2)
    Thread.sleep(100000)
  }

  ignore("Superpixeling should work properly on grocery img") {
    val groceryImg: BufferedImage = ImageIO.read(
      new File(s"$filesRoot/Images/Grocery/testImages/WIN_20160803_11_28_42_Pro.jpg"))
    val spGrocery = new Superpixel(groceryImg, 100, 130)
    Superpixel.displayImage(spGrocery.getClusteredImage)
    Thread.sleep(180000)
  }

  test("Censored clusters' pixels should be black in the censored image") {
    for (i <- states.indices if !states(i)) {
      allClusters(i).pixels.foreach { case (x: Int, y: Int) =>
        val color = new Color(censoredImg.getRGB(x, y))
        assert(color.getRed === 0 && color.getGreen === 0 && color.getBlue === 0)
      }
    }
  }

} 
Example 7
Source File: WriteOutDemoPlots.scala    From evilplot   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.cibo.evilplot

import java.io.File
import java.nio.file.{Files, Paths}

import com.cibo.evilplot.demo.DemoPlots
import javax.imageio.ImageIO
import org.scalatest.{FunSpec, Matchers}
import com.cibo.evilplot.geometry.Drawable
import scala.util.Try

object WriteOutDemoPlots {
  def apply(args:Array[String]):Unit = 
    for(plotName <- args; plot <- DemoPlots.get(Symbol(plotName)))
       plot write new java.io.File(s"$plotName.png")
}
class WriteOutDemoPlots extends FunSpec with Matchers {

  //-- DemoPlot name and ratio of colored pixels (to represent an simple hash)
  val plots = Seq(
    'linePlot -> 0.01498,
    'heatmap -> 0.81790,
    'pieChart -> 0.44209,
    'clusteredBarChart -> 0.31712,
    'clusteredStackedBarChart -> 0.30259,
    'stackedBarChart -> 0.35687,
    'barChart -> 0.18869,
    'functionPlot -> 0.01728,
    'markerPlot -> 0.01008,
    'crazyPlot -> 0.10755,
    'facetedPlot -> 0.04951,
    'marginalHistogram -> 0.04002,
    'scatterPlot -> 0.02314,
    'boxPlot -> 0.29182,
    'facetedPlot -> 0.04951,
    'histogramOverlay -> 0.32281
  )

  val tmpPathOpt = {
    val tmpPath = Paths.get("/tmp/evilplot")
    if (Files.notExists(tmpPath)) Try{Files.createDirectories(tmpPath)}
    if(Files.notExists(tmpPath)) None else {
      println(s"Saving rendered png's to $tmpPath")
      Some(tmpPath)
    }
  }

  describe("Demo Plots") {
    it("render to consistent murmur hash") {
      for { (name, ratioTruth) <- plots; plot <- DemoPlots.get(name)} {

        val bi = plot.asBufferedImage

        def isColored(c:Int):Boolean = {
          val r = (c >> 16) & 0xFF;
          val g = (c >> 8) & 0xFF;
          val b = (c >> 8) & 0xFF;
          r + g + b > 10
        }

        val ratio:Double = {
          val pixels = (for(x <- 0 until bi.getWidth; y <- 0 until bi.getHeight) yield bi.getRGB(x,y)).toArray
          pixels.count(isColored).toDouble/pixels.size
        }

        val delta = math.abs(ratioTruth - ratio)
        println(f"""$name -> $ratio%5.5f, //delta = $delta%8.8f""")
        assert(delta < 0.0015, s"$name out of range $ratio != $ratioTruth")

        //--write img to file if the tmp path is available
        for(_ <- None; tmpPath <- tmpPathOpt){
          val file = new File(s"${tmpPath.toAbsolutePath.toString}/${name.name}.png")
          ImageIO.write(bi, "png", file)
          file.exists() shouldBe true
        }
      }
    }
  }
} 
Example 8
Source File: Runtime.scala    From scastie   with Apache License 2.0 5 votes vote down vote up
package com.olegych.scastie.api
package runtime

import javax.imageio.ImageIO
import java.io.{ByteArrayOutputStream, File}
import java.util.Base64
import java.awt.image.BufferedImage

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Runtime extends SharedRuntime {
  def render[T](a: T)(implicit _ct: ClassTag[T] = null, _tt: TypeTag[T] = null): Render = {
    val ct = Option(_ct)
    val tt = Option(_tt)
    super.render(a, tt.map(_.tpe.toString).orElse(ct.map(_.toString)).getOrElse(""))
  }

  def image(path: String): Html = {
    val in = ImageIO.read(new File(path))
    toBase64(in)
  }

  def toBase64(in: BufferedImage): Html = {
    val width = in.getWidth
    val os = new ByteArrayOutputStream
    val b64 = Base64.getEncoder.wrap(os)
    ImageIO.write(in, "png", b64)
    val encoded = os.toString("UTF-8")

    Html(
      s"""
      <div style="width:${width}px; margin:0 auto">
        <image src="data:image/png;base64,$encoded">
      </div>
      """,
      folded = true
    )
  }
} 
Example 9
Source File: TestOCR.scala    From AppCrawler   with Apache License 2.0 5 votes vote down vote up
class TestOCR extends FunSuite{

  test("test ocr"){
    val api=new Tesseract()
    api.setDatapath("/Users/seveniruby/Downloads/")
    api.setLanguage("eng+chi_sim")
    val img=new java.io.File("/Users/seveniruby/temp/google-test7.png")
    val imgFile=ImageIO.read(img)
    val graph=imgFile.createGraphics()
    graph.setStroke(new BasicStroke(5))

    val result=api.doOCR(img)

    val words=api.getWords(imgFile, TessPageIteratorLevel.RIL_WORD).toList
    words.foreach(word=>{

      val box=word.getBoundingBox
      val x=box.getX.toInt
      val y=box.getY.toInt
      val w=box.getWidth.toInt
      val h=box.getHeight.toInt

      graph.drawRect(x, y, w, h)
      graph.drawString(word.getText, x, y)

      println(word.getBoundingBox)
      println(word.getText)
    })
    graph.dispose()
    ImageIO.write(imgFile, "png", new java.io.File(s"${img}.mark.png"))



    println(result)

  }

}
*/ 
Example 10
Source File: FileOutputImpl.scala    From chatoverflow   with Eclipse Public License 2.0 5 votes vote down vote up
package org.codeoverflow.chatoverflow.requirement.service.file.impl

import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream

import javax.imageio.ImageIO
import org.codeoverflow.chatoverflow.WithLogger
import org.codeoverflow.chatoverflow.api.io.output.FileOutput
import org.codeoverflow.chatoverflow.registry.Impl
import org.codeoverflow.chatoverflow.requirement.impl.OutputImpl
import org.codeoverflow.chatoverflow.requirement.service.file.FileConnector

@Impl(impl = classOf[FileOutput], connector = classOf[FileConnector])
class FileOutputImpl extends OutputImpl[FileConnector] with FileOutput with WithLogger {

  override def saveFile(content: String, pathInResources: String): Boolean = {
    sourceConnector.get.saveFile(pathInResources, content)
  }

  override def saveBinaryFile(bytes: Array[Byte], pathInResources: String): Boolean = {
    sourceConnector.get.saveBinaryFile(pathInResources, bytes)
  }

  override def saveImage(image: BufferedImage, format: String, pathInResources: String): Boolean = {
    val bao = new ByteArrayOutputStream()
    ImageIO.write(image, format.toLowerCase, bao)
    sourceConnector.get.saveBinaryFile(s"$pathInResources.${format.toLowerCase}", bao.toByteArray)
  }

  override def createDirectory(folderName: String): Boolean = {
    sourceConnector.get.createDirectory(folderName)
  }

  override def exists(pathInResources: String): Boolean = {
    sourceConnector.get.exists(pathInResources)
  }

  override def delete(pathInResources: String): Boolean = {
    sourceConnector.get.delete(pathInResources)
  }

  override def start() = true

  
  override def stop(): Boolean = true
} 
Example 11
Source File: FileInputImpl.scala    From chatoverflow   with Eclipse Public License 2.0 5 votes vote down vote up
package org.codeoverflow.chatoverflow.requirement.service.file.impl

import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.util.Optional

import javax.imageio.ImageIO
import org.codeoverflow.chatoverflow.WithLogger
import org.codeoverflow.chatoverflow.api.io.input.FileInput
import org.codeoverflow.chatoverflow.registry.Impl
import org.codeoverflow.chatoverflow.requirement.impl.InputImpl
import org.codeoverflow.chatoverflow.requirement.service.file.FileConnector

@Impl(impl = classOf[FileInput], connector = classOf[FileConnector])
class FileInputImpl extends InputImpl[FileConnector] with FileInput with WithLogger {

  override def getFile(pathInResources: String): Optional[String] = Optional.ofNullable(sourceConnector.get.getFile(pathInResources).orNull)

  override def getBinaryFile(pathInResources: String): Optional[Array[Byte]] = Optional.ofNullable(sourceConnector.get.getBinaryFile(pathInResources).orNull)

  override def getImage(pathInResources: String): Optional[BufferedImage] = {
    val data = sourceConnector.get.getBinaryFile(pathInResources)
    if (data.isEmpty) {
      None
    }
    val bis = new ByteArrayInputStream(data.get)
    Optional.of(ImageIO.read(bis))
  }

  override def start(): Boolean = true

  
  override def stop(): Boolean = true
} 
Example 12
Source File: ImageSize.scala    From docspell   with GNU General Public License v3.0 5 votes vote down vote up
package docspell.files

import java.io.{ByteArrayInputStream, InputStream}
import java.nio.file.Path
import javax.imageio.stream.{FileImageInputStream, ImageInputStream}
import javax.imageio.{ImageIO, ImageReader}

import scala.jdk.CollectionConverters._
import scala.util.{Try, Using}

import cats.effect._
import cats.implicits._
import fs2.Stream

object ImageSize {

  
  def get[F[_]: Sync](data: Stream[F, Byte]): F[Option[Dimension]] =
    data.take(768).compile.to(Array).map { ar =>
      val iis = ImageIO.createImageInputStream(new ByteArrayInputStream(ar))
      if (iis == null) sys.error("no reader given for the array")
      else getDimension(iis)
    }

  private def getDimension(in: ImageInputStream): Option[Dimension] =
    ImageIO
      .getImageReaders(in)
      .asScala
      .to(LazyList)
      .collectFirst(Function.unlift { reader =>
        val dim = getDimension(in, reader).toOption
        reader.dispose()
        dim
      })

  private def getDimension(
      in: ImageInputStream,
      reader: ImageReader
  ): Either[Throwable, Dimension] =
    Try {
      reader.setInput(in)
      val width  = reader.getWidth(reader.getMinIndex)
      val height = reader.getHeight(reader.getMinIndex)
      Dimension(width, height)
    }.toEither
} 
Example 13
Source File: BossNameTranslator.scala    From gbf-raidfinder   with MIT License 5 votes vote down vote up
package walfie.gbf.raidfinder.server

import akka.agent.Agent
import com.pastebin.Pj9d8jt5.ImagePHash
import java.awt.image.BufferedImage
import java.net.URL
import javax.imageio.ImageIO
import monix.execution.Scheduler
import monix.reactive._
import monix.reactive.subjects.ConcurrentSubject
import scala.concurrent.{ExecutionContext, Future}
import walfie.gbf.raidfinder.domain._
import walfie.gbf.raidfinder.util.BlockingIO

trait BossNameTranslator {
  import BossNameTranslator.Translation

  def translate(bossName: BossName): Option[BossName]
  def update(latestBosses: Map[BossName, RaidBoss]): Future[Unit]
  def observable(): Observable[Translation]
}

object BossNameTranslator {
  case class Translation(from: BossName, to: BossName)
}


  private def croppedImageFromUrl(url: URL): BufferedImage = {
    // TODO: Use a real HTTP client to get the image
    val image = ImageIO.read(url.openStream())
    image.getSubimage(0, 0, image.getWidth(), image.getHeight() * 3 / 4);
  }

  // This assumes there are only two languages (which is true currently)
  private def findTranslation(newData: TranslationData): Option[BossName] = {
    translationDataAgent.get.values.find { existingData =>
      newData.hash == existingData.hash &&
        newData.language != existingData.language &&
        newData.level == existingData.level
    }.map(_.name)
  }
}

object ImageBasedBossNameTranslator {
  case class TranslationData(name: BossName, level: Int, language: Language, hash: ImageHash)

  case class ImageHash(value: Long) extends AnyVal
} 
Example 14
Source File: ImageSaver.scala    From Muse-CGH   with MIT License 5 votes vote down vote up
package utilities

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


object ImageSaver {
  def saveImage(image: RenderedImage, path: String): Option[String] ={
    try {
      val (name, ext) = nameAndExtension(path, "png")
      val file = new File(name+s".$ext")
      ImageIO.write(image, ext, file)
      Some(file.getAbsolutePath)
    }catch {
      case e: Throwable =>
        println(s"failed to save image with error: $e")
        None
    }
  }

  def nameAndExtension(s: String, defaultExt:String) = {
    val names = s.split("\\.")
    if(names.length == 1){
      (names.head, defaultExt)
    }else{
      (names(names.length-2), names.last)
    }
  }
} 
Example 15
Source File: Bencharts.scala    From collection-strawman   with Apache License 2.0 5 votes vote down vote up
package strawman.collection

import javax.imageio.ImageIO

import org.jfree.chart.JFreeChart
import org.jfree.chart.axis.{LogAxis, LogarithmicAxis, NumberAxis}
import org.jfree.chart.plot.XYPlot
import org.jfree.chart.renderer.xy.XYErrorRenderer
import org.jfree.data.xy.{YIntervalSeries, YIntervalSeriesCollection}
import play.api.libs.json.{JsObject, Json}
import sbt._

object Bencharts {

  
  def apply(jmhReport: File, yAxisTitle: String, targetDir: File): Unit = {
    val json = Json.parse(IO.read(jmhReport))

    json.as[List[JsObject]]
      .groupBy { result =>
        val name = (result \ "benchmark").as[String]
        val benchmark = name.reverse.takeWhile(_ != '.').reverse
        benchmark // Benchmark name (e.g. "cons", "foreach", "map")
      }
      .foreach { case (benchmark, results) =>
        val seriess =
          results
            // group by concrete collection type
            .groupBy(result => (result \ "benchmark").as[String].stripSuffix(benchmark))
            .map { case (collectionType, iterations) =>
              val ySeries = new YIntervalSeries(collectionType)
              // each benchmark has been run with several collection sizes (8, 64, 512, etc.)
              // we add a point for each of these iterations
              for (iteration <- iterations) {
                ySeries.add(
                  (iteration \ "params" \ "size").as[String].toDouble,
                  (iteration \ "primaryMetric" \ "score").as[Double],
                  (iteration \ "primaryMetric" \ "scoreConfidence").apply(0).as[Double],
                  (iteration \ "primaryMetric" \ "scoreConfidence").apply(1).as[Double]
                )
              }
              ySeries
            }

        val xAxis = new LogarithmicAxis("Size")
        xAxis.setAllowNegativesFlag(true)
        val yAxis = new LogarithmicAxis(yAxisTitle)
        yAxis.setAllowNegativesFlag(true)

        val col = new YIntervalSeriesCollection()
        val renderer = new XYErrorRenderer
        for ((series, i) <- seriess.zipWithIndex) {
          col.addSeries(series)
          renderer.setSeriesLinesVisible(i, true)
        }

        val plot = new XYPlot(
          col,
          xAxis, yAxis,
          renderer
        )

        val chart = new JFreeChart(
          benchmark,
          JFreeChart.DEFAULT_TITLE_FONT,
          plot,
          true
        )

        ImageIO.write(
          chart.createBufferedImage(800, 600),
          "png",
          targetDir / s"$benchmark.png"
        )

      }
  }

} 
Example 16
Source File: ImageLoaderUtils.scala    From keystone   with Apache License 2.0 5 votes vote down vote up
package keystoneml.loaders

import java.awt.image.BufferedImage
import java.io.{InputStream, ByteArrayInputStream}
import java.net.URI
import java.util.zip.GZIPInputStream
import javax.imageio.ImageIO

import keystoneml.loaders.VOCLoader._
import org.apache.commons.compress.archivers.ArchiveStreamFactory
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import keystoneml.pipelines.Logging
import keystoneml.utils._

import scala.collection.mutable.ArrayBuffer
import scala.reflect.ClassTag

object ImageLoaderUtils extends Logging {
  
  def loadFiles[L, I <: AbstractLabeledImage[L] : ClassTag](
      filePathsRDD: RDD[URI],
      labelsMap: String => L,
      imageBuilder: (Image, L, Option[String]) => I, // TODO(etrain): We can probably do this with implicits.
      namePrefix: Option[String] = None): RDD[I] = {
    filePathsRDD.flatMap(fileUri => loadFile(fileUri, labelsMap, imageBuilder, namePrefix))
  }

  private def loadFile[L, I <: AbstractLabeledImage[L]](
      fileUri: URI,
      labelsMap: String => L,
      imageBuilder: (Image, L, Option[String]) => I,
      namePrefix: Option[String]): Iterator[I] = {
    val filePath = new Path(fileUri)
    val conf = new Configuration(true)
    val fs = FileSystem.get(filePath.toUri(), conf)
    val fStream = fs.open(filePath)

    val tarStream = new ArchiveStreamFactory().createArchiveInputStream(
      "tar", fStream).asInstanceOf[TarArchiveInputStream]

    var entry = tarStream.getNextTarEntry()
    val imgs = new ArrayBuffer[I]
    while (entry != null) {
      if (!entry.isDirectory && (namePrefix.isEmpty || entry.getName.startsWith(namePrefix.get))) {
        var offset = 0
        var ret = 0
        val content = new Array[Byte](entry.getSize().toInt)
        while (ret >= 0 && offset != entry.getSize()) {
          ret = tarStream.read(content, offset, content.length - offset)
          if (ret >= 0) {
            offset += ret
          }
        }

        val bais = new ByteArrayInputStream(content)

        val image = ImageUtils.loadImage(bais).map { img =>
          imageBuilder(img, labelsMap(entry.getName), Some(entry.getName))
        }

        imgs ++= image
      }
      entry = tarStream.getNextTarEntry()
    }

    imgs.iterator
  }
} 
Example 17
Source File: SquaringImage.scala    From Scala-Machine-Learning-Projects   with MIT License 5 votes vote down vote up
package Yelp.Preprocessor

import org.imgscalr._
import java.io.File
import javax.imageio.ImageIO

object SquaringImage {
  def main(args: Array[String]): Unit = {
    def makeSquare(img: java.awt.image.BufferedImage): java.awt.image.BufferedImage = {
      val w = img.getWidth
      val h = img.getHeight
      val dim = List(w, h).min

      img match {
        case x if w == h => img
        case x if w > h => Scalr.crop(img, (w - h) / 2, 0, dim, dim)
        case x if w < h => Scalr.crop(img, 0, (h - w) / 2, dim, dim)
      }
    }

    val myimg = ImageIO.read(new File("data/images/train/147.jpg"))
    val myimgSquare = makeSquare(myimg)
    ImageIO.write(myimgSquare, "jpg", new File("data/images/preprocessed/147square.jpg"))
  }
} 
Example 18
Source File: ImageResize.scala    From Scala-Machine-Learning-Projects   with MIT License 5 votes vote down vote up
package Yelp.Preprocessor

import org.imgscalr._
import java.io.File
import javax.imageio.ImageIO

object ImageResize {
  def main(args: Array[String]): Unit = {

    def resizeImg(img: java.awt.image.BufferedImage, width: Int, height: Int) = {
      Scalr.resize(img, Scalr.Method.BALANCED, width, height)
    }

    val testImage = ImageIO.read(new File("data/images/train/147.jpg"))

    val testImage32 = resizeImg(testImage, 32, 32)
    val testImage64 = resizeImg(testImage, 64, 64)
    val testImage128 = resizeImg(testImage, 128, 128)
    val testImage256 = resizeImg(testImage, 256, 256)

    ImageIO.write(testImage32, "jpg", new File("data/images/preprocessed/147resize32.jpg"))
    ImageIO.write(testImage64, "jpg", new File("data/images/preprocessed/147resize64.jpg"))
    ImageIO.write(testImage128, "jpg", new File("data/images/preprocessed/147resize128.jpg"))
    ImageIO.write(testImage256, "jpg", new File("data/images/preprocessed/147resize256.jpg"))
  }
} 
Example 19
Source File: imageFeatureExtractor.scala    From Scala-Machine-Learning-Projects   with MIT License 5 votes vote down vote up
package Yelp.Preprocessor

import java.io.File
import javax.imageio.ImageIO
import scala.util.matching.Regex
import imageUtils._

object imageFeatureExtractor {  
  
  
  def processImages(imgs: List[String], resizeImgDim: Int = 128, nPixels: Int = -1): Map[Int, Vector[Int]] = {       
    imgs.map(x => 
      patt_get_jpg_name.findAllIn(x).mkString.toInt -> { 
        val img0 = ImageIO.read(new File(x))
         .makeSquare
         .resizeImg(resizeImgDim, resizeImgDim) // (128, 128)
         .image2gray
       if(nPixels != -1) img0.slice(0, nPixels)
       else img0
     }   
   ).filter( x => x._2 != ())
    .toMap    
  }  
} 
Example 20
Source File: GrayscaleConverter.scala    From Scala-Machine-Learning-Projects   with MIT License 5 votes vote down vote up
package Yelp.Preprocessor

import java.io.File
import javax.imageio.ImageIO
import java.awt.Color

object GrayscaleConverter {
  def main(args: Array[String]): Unit = {
    def pixels2Gray(R: Int, G: Int, B: Int): Int = (R + G + B) / 3

    def makeGray(testImage: java.awt.image.BufferedImage): java.awt.image.BufferedImage = {
      val w = testImage.getWidth
      val h = testImage.getHeight
      for {
        w1 <- (0 until w).toVector
        h1 <- (0 until h).toVector
      } yield {
        val col = testImage.getRGB(w1, h1)
        val R = (col & 0xff0000) / 65536
        val G = (col & 0xff00) / 256
        val B = (col & 0xff)
        val graycol = pixels2Gray(R, G, B)
        testImage.setRGB(w1, h1, new Color(graycol, graycol, graycol).getRGB)
      }
      testImage
    }

    val testImage = ImageIO.read(new File("data/images/preprocessed/147square.jpg"))
    val grayImage = makeGray(testImage)
    ImageIO.write(grayImage, "jpg", new File("data/images/preprocessed/147gray.jpg"))
  }
} 
Example 21
Source File: File.scala    From nescala   with GNU General Public License v2.0 5 votes vote down vote up
package com.owlandrews.nescala.helpers

import com.owlandrews.nescala.Console

object File {
  import java.io.File
  import java.net.URL
  import java.io.{FileFilter, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream}
  import javax.imageio.ImageIO

  import scala.util.Try
  import scala.xml.XML
  import scala.language.postfixOps

  import sys.process._

  import com.typesafe.config.ConfigFactory

  def Download(url: String, filename: String) = (for{
    url <- Try(new URL(url))
    conn <- Try(url.openConnection().connect())
    file <- Try(new File(filename))
  } yield Try(url  #> file !!)) map {x => new File(filename)}

  def Writer(filename: String)(op: java.io.PrintWriter => Unit) = {
    val p = new java.io.PrintWriter(new File(filename))
    try op(p)
    finally p.close()
  }

  def Write(filename: String, content: String) = {
    val res = new java.io.PrintWriter(new File(filename))
    res.write(content)
    res.close()
  }

  def Filter = new FileFilter {
    override def accept(pathname: File): Boolean = pathname.getName.toLowerCase.endsWith(".nes")
  }

  def Image(file:Try[File]) = file.map(ImageIO.read)

  def Image(filename:String) = Try(ImageIO.read(resource(filename)))

  def Xml(filename:String) = XML.load(resource("/database.xml"))

  def Config(filename:String) = {
    val file = new File(filename)
    file.exists() match {
      case true => ConfigFactory.parseFile(file)
      case false => ConfigFactory.empty()
    }
  }

  def SaveState(console:Console) = {
    val fos = new FileOutputStream(s"$ApplicationFolder/${console.cartridge.CRC}.save")
    val oos = new ObjectOutputStream(fos)

    oos.writeObject(console)
    oos.close()
  }

  def LoadState(crc:String):Try[Console] = Try {
    val fis = new FileInputStream(s"$ApplicationFolder/$crc.save")
    val ois = new ObjectInputStreamWithCustomClassLoader(fis)

    val console = ois.readObject.asInstanceOf[Console]
    ois.close()
    console
  }

  // Taken from: https://gist.github.com/ramn/5566596
  private class ObjectInputStreamWithCustomClassLoader(fileInputStream: FileInputStream) extends ObjectInputStream(fileInputStream) {
    override def resolveClass(desc: java.io.ObjectStreamClass): Class[_] = {
      try { Class.forName(desc.getName, false, getClass.getClassLoader) }
      catch { case ex: ClassNotFoundException => super.resolveClass(desc) }
    }
  }

  lazy val ApplicationFolder: File = {
    val settingDirectory = System.getProperty("user.home") + "/.nescala"
    val settings = new java.io.File(settingDirectory)
    if (!settings.exists()) settings.mkdir()
    settings
  }

  private def resource(filename:String) = getClass.getResourceAsStream(filename)
} 
Example 22
Source File: COCODatasetSpec.scala    From BigDL   with Apache License 2.0 5 votes vote down vote up
package com.intel.analytics.bigdl.dataset.segmentation

import com.intel.analytics.bigdl.tensor.Tensor
import com.intel.analytics.bigdl.transform.vision.image.{ImageFeature, RoiImageInfo}
import com.intel.analytics.bigdl.transform.vision.image.label.roi.RoiLabel
import java.awt.image.DataBufferByte
import java.io.{File, FileInputStream}
import javax.imageio.ImageIO
import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers}

class COCODatasetSpec extends FlatSpec with Matchers with BeforeAndAfter {

  private def processPath(path: String): String = {
    if (path.contains(":")) {
      path.substring(1)
    } else {
      path
    }
  }

  val resourcePath: String = processPath(getClass.getClassLoader.getResource("coco").getPath)
  val dataSet: COCODataset = COCODataset.load(resourcePath
      + File.separator + "cocomini.json", resourcePath)

  "COCODataset" should "correctly be loaded" in {
    dataSet.images.length should be (5)
    dataSet.annotations.length should be (6)
    val cateIdx = Array(53, 53, 53, 1, 19, 1).toIterator
    val sizes = Array((428, 640), (480, 640), (427, 640), (480, 640), (427, 640)).toIterator
    for (anno <- dataSet.annotations) {
      anno.image.id should be (anno.imageId)
      dataSet.categoryId2Idx(anno.categoryId) should be (cateIdx.next())
      anno.categoryIdx should be (dataSet.categoryId2Idx(anno.categoryId))
      if (anno.isCrowd) {
        anno.segmentation.isInstanceOf[COCORLE] should be (true)
      } else {
        anno.segmentation.isInstanceOf[COCOPoly] should be (true)
        val poly = anno.segmentation.asInstanceOf[COCOPoly]
        poly.height should be (anno.image.height)
        poly.width should be (anno.image.width)
      }
    }
    for (img <- dataSet.images) {
      val size = sizes.next()
      img.height should be (size._1)
      img.width should be (size._2)
    }
    for (i <- 1 to dataSet.categories.length) {
      val cate = dataSet.getCategoryByIdx(i)
      dataSet.categoryId2Idx(cate.id) should be (i)
    }
  }

  "COCODataset.toImageFeatures" should "correctly work" in {
    val cateIdx = Array(1, 19, 53, 53, 53, 1).toIterator
    val sizes = Array((428, 640, 3), (480, 640, 3), (427, 640, 3), (480, 640, 3),
      (427, 640, 3)).toIterator
    val uri = Array("COCO_val2014_000000153344.jpg", "COCO_val2014_000000091136.jpg",
      "COCO_val2014_000000558840.jpg", "COCO_val2014_000000200365.jpg",
      "COCO_val2014_000000374530.jpg"
    ).toIterator
    val isCrowd = Array(1f, 1f, 0f, 0f, 0f, 1f).toIterator
    dataSet.toImageFeatures.foreach(imf => {
      imf.getOriginalSize should be (sizes.next())
      val iscr = imf[Tensor[Float]](RoiImageInfo.ISCROWD)

      val roilabel = imf.getLabel[RoiLabel]
      roilabel.classes.size() should be (iscr.size())
      for(i <- 1 to iscr.nElement()) {
        iscr.valueAt(i) should be (isCrowd.next())
        roilabel.classes.valueAt(i) should be (cateIdx.next())
      }
      roilabel.bboxes.size() should be (Array(roilabel.classes.size(1), 4))

      val inputStream = new FileInputStream(resourcePath + File.separator + uri.next())
      val image = ImageIO.read(inputStream)
      val rawdata = image.getRaster.getDataBuffer.asInstanceOf[DataBufferByte].getData()
      require(java.util.Arrays.equals(rawdata, imf[Array[Byte]](ImageFeature.bytes)))
    })
  }

  "COCOImage.toTable" should "correctly work" in {
    val cateIdx = Array(1, 19, 53, 53, 53, 1).toIterator
    val sizes = Array((428, 640, 3), (480, 640, 3), (427, 640, 3), (480, 640, 3),
      (427, 640, 3)).toIterator
    val isCrowd = Array(1f, 1f, 0f, 0f, 0f, 1f).toIterator
    dataSet.images.map(_.toTable).foreach(tab => {
      RoiImageInfo.getOrigSize(tab) should be (sizes.next())
      val iscr = RoiImageInfo.getIsCrowd(tab)
      val classes = RoiImageInfo.getClasses(tab)
      classes.size() should be (iscr.size())
      for(i <- 1 to iscr.nElement()) {
        iscr.valueAt(i) should be (isCrowd.next())
        classes.valueAt(i) should be (cateIdx.next())
      }
      RoiImageInfo.getBBoxes(tab).size() should be (Array(classes.size(1), 4))

    })
  }

} 
Example 23
Source File: Utils.scala    From BigDL   with Apache License 2.0 5 votes vote down vote up
package com.intel.analytics.bigdl.dataset.image

import java.awt.image.BufferedImage
import java.awt.{BasicStroke, Color, Font, Graphics2D}
import java.io.File
import java.nio.file.Paths
import javax.imageio.ImageIO

import com.intel.analytics.bigdl.tensor.Tensor


  def visDetection(imagePath: String, clsname: String,
    scores: Tensor[Float], bboxes: Tensor[Float],
    thresh: Float = 0.3f, outPath: String = "data/demo"): Unit = {
    val f = new File(outPath)
    if (!f.exists()) {
      f.mkdirs()
    }
    val path = Paths.get(outPath,
      s"${ clsname }_${ imagePath.substring(imagePath.lastIndexOf("/") + 1) }").toString
    vis(imagePath, clsname, scores, bboxes, path, thresh)
  }
}