java.awt.image.BufferedImage Scala Examples

The following examples show how to use java.awt.image.BufferedImage. 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: 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 3
Source File: MNISTVisualizer.scala    From dl4scala   with MIT License 5 votes vote down vote up
package org.dl4scala.examples.feedforward.anomalydetection

import java.awt.{GridLayout, Image}
import java.awt.image.BufferedImage
import javax.swing.{ImageIcon, JFrame, JLabel, JPanel}

import org.nd4j.linalg.api.ndarray.INDArray

import scala.collection.mutable.ArrayBuffer


class MNISTVisualizer(imageScale: Double, digits: ArrayBuffer[INDArray], title: String, gridWidth: Int) {
  def this(imageScale: Double, digits: ArrayBuffer[INDArray], title: String) = {
    this(imageScale, digits, title, 5)
  }

  def visualize(): Unit = {
    val frame = new JFrame
    frame.setTitle(title)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    val panel = new JPanel
    panel.setLayout(new GridLayout(0, gridWidth))
    val list = getComponents
    for (image <- list) {
      panel.add(image)
    }
    frame.add(panel)
    frame.setVisible(true)
    frame.pack()
  }

  def getComponents: ArrayBuffer[JLabel] = {
    val images = new ArrayBuffer[JLabel]()
    for (arr <- digits) {
      val bi = new BufferedImage(28, 28, BufferedImage.TYPE_BYTE_GRAY)
      for(i <- 0 until 784) {
        bi.getRaster.setSample(i % 28, i / 28, 0, (255 * arr.getDouble(i)).asInstanceOf[Int])
      }
      val orig = new ImageIcon(bi)
      val imageScaled = orig.getImage.getScaledInstance((imageScale * 28).asInstanceOf[Int],
        (imageScale * 28).asInstanceOf[Int], Image.SCALE_REPLICATE)
      val scaled = new ImageIcon(imageScaled)
      images.append(new JLabel(scaled))
    }
    images
  }
} 
Example 4
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 5
Source File: Graphics2DRenderContextSpec.scala    From evilplot   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.cibo.evilplot.geometry

import java.awt.image.BufferedImage
import java.awt.{BasicStroke, Color, Graphics2D}

import org.scalatest.{FunSpec, Matchers}

class Graphics2DRenderContextSpec extends FunSpec with Matchers with Graphics2DSupport {
  describe("state stack operations") {
    it("The state should be the same before and after a stack op.") {
      val graphics = Graphics2DTestUtils.graphics2D
      val ctx = Graphics2DRenderContext(graphics)
      val GraphicsState(initialTransform, initialFill, initialColor, initialStroke) =
        ctx.initialState
      Graphics2DRenderContext.applyOp(ctx) {
        ctx.graphics.translate(34, 20)
        ctx.graphics.setPaint(Color.BLUE)
        ctx.graphics.setStroke(new BasicStroke(3))
      }
      ctx.graphics.getTransform shouldBe initialTransform
      ctx.fillColor shouldBe initialFill
      ctx.strokeColor shouldBe initialColor
      ctx.graphics.getStroke shouldBe initialStroke
    }
  }
}

object Graphics2DTestUtils {
  def graphics2D: Graphics2D = {
    val bi = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB)
    bi.createGraphics()
  }
} 
Example 6
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 play.api.libs.json.Json

import org.scalajs.dom.raw.HTMLElement

import java.util.UUID

import java.awt.image.BufferedImage

import scala.reflect.ClassTag

object Runtime extends SharedRuntime {
  def write(in: Either[Option[RuntimeError], List[Instrumentation]]): String = {
    Json.stringify(Json.toJson(ScalaJsResult(in)))
  }
  def render[T](a: T, attach: HTMLElement => UUID)(implicit _ct: ClassTag[T] = null): Render = {
    val ct = Option(_ct)
    a match {
      case element: HTMLElement => {
        val uuid = attach(element)
        AttachedDom(uuid.toString)
      }
      case _ => super.render(a, ct.map(_.toString).getOrElse(""))
    }
  }

  def image(path: String): Html =
    throw new Exception("image(path: String): Html works only on the jvm")

  def toBase64(in: BufferedImage): Html =
    throw new Exception(
      "toBase64(in: BufferedImage): Html works only on the jvm"
    )
} 
Example 7
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 8
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 9
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 10
Source File: Figure.scala    From pdffigures2   with Apache License 2.0 5 votes vote down vote up
package org.allenai.pdffigures2

import java.awt.image.BufferedImage
import org.allenai.common.{ Enum, EnumCompanion }

sealed abstract class FigureType(id: String) extends Enum[FigureType]
object FigureType extends EnumCompanion[FigureType] {
  case object Table extends FigureType("Table")
  case object Figure extends FigureType("Figure")
  register(Figure, Table)
}

case class CaptionParagraph(name: String, figType: FigureType, page: Int, paragraph: Paragraph) {
  def boundary: Box = paragraph.boundary
  def startLineNumber: Int = paragraph.startLineNumber
  def text: String = Paragraph.convertToNormalizedString(paragraph)
}

object Caption {
  def apply(captionParagraph: CaptionParagraph): Caption = {
    Caption(
      captionParagraph.name,
      captionParagraph.figType,
      captionParagraph.page,
      captionParagraph.text,
      captionParagraph.boundary
    )
  }
}
case class Caption(name: String, figType: FigureType, page: Int, text: String, boundary: Box)

case class Figure(
  name: String,
  figType: FigureType,
  page: Int,
  caption: String,
  imageText: Seq[String],
  captionBoundary: Box,
  regionBoundary: Box
)


case class SavedFigure(
  name: String,
  figType: FigureType,
  page: Int,
  caption: String,
  imageText: Seq[String],
  captionBoundary: Box,
  regionBoundary: Box,
  renderURL: String,
  renderDpi: Int
)

case class FiguresInDocument(figures: Seq[Figure], failedCaptions: Seq[Caption])

case class RasterizedFiguresInDocument(figures: Seq[RasterizedFigure], failedCaptions: Seq[Caption]) 
Example 11
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 12
Source File: MuseCharPainter.scala    From Muse-CGH   with MIT License 5 votes vote down vote up
package main

import java.awt.image.BufferedImage
import java.awt.{RenderingHints, Color, Graphics2D}

import utilities.Vec2


class MuseCharPainter(g2d: Graphics2D, pixelPerUnit: Double, displayPixelScale: Double, imageOffset: Vec2,
                    dotsPerUnit:Double, thicknessScale: Double) {

  def bufferOffset = Vec2(2,2)
  def paintWordWithBuffering(segs: IndexedSeq[WidthCurve], offset: Vec2, color: Color, width: Double, height: Double): Unit = {
    val s = pixelPerUnit*displayPixelScale

    def pointTrans(p: Vec2) = p*s

    val bufferWidth = (width+2*bufferOffset.x)*s
    val bufferHeight = (height+2*bufferOffset.y)*s

    val buffer = new BufferedImage(bufferWidth.toInt, bufferHeight.toInt, BufferedImage.TYPE_INT_ARGB)
    val bufferG = buffer.getGraphics.asInstanceOf[Graphics2D]

    val drawer = new CurveDrawer(bufferG, pointTrans, pixelPerUnit*displayPixelScale, dotsPerUnit, thicknessScale)

    drawer.setColor(color)
    segs.foreach{ case WidthCurve(curve, wf) =>
      drawer.drawColorfulCurve(curve, wf, None)
    }


    val dest = (offset-bufferOffset)*s

    g2d.drawImage(buffer, dest.x.toInt, dest.y.toInt, null)
  }

  def draw(segs: IndexedSeq[WidthCurve], offset: Vec2, color: Color): Unit = {
    def pointTrans(p: Vec2): Vec2 = {
      val s = pixelPerUnit*displayPixelScale
      (p+offset)*s + imageOffset*displayPixelScale
    }

    val drawer = new CurveDrawer(g2d, pointTrans, pixelPerUnit*displayPixelScale, dotsPerUnit, thicknessScale)

    drawer.setColor(color)
    segs.foreach{ case WidthCurve(curve, wf) =>
      drawer.drawCurveWithTimeUsed(curve, wf)
    }
  }

  def drawAnimation(bufferScaleFactor: Double, timeUsed: Double => Boolean = (_) => false)(
    segs: IndexedSeq[WidthCurve], offset: Vec2, color: Color): Boolean = {
    val s = pixelPerUnit*displayPixelScale
    def pointTrans(p: Vec2): Vec2 = {
      ((p+offset)*s + imageOffset*displayPixelScale)* bufferScaleFactor
    }

    val drawer = new CurveDrawer(g2d, pointTrans, s, dotsPerUnit, thicknessScale)

    drawer.setColor(color)

    var lastPos = Vec2.zero
    segs.foreach{case WidthCurve(curve, wf) =>
      val dis = (curve.p0 - lastPos).length
      lastPos = curve.p0

      if(timeUsed(dis) ||
        drawer.drawCurveWithTimeUsed(curve, wf, timeUsed)) return true
    }
    false
  }
} 
Example 13
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 14
Source File: ImageConversions.scala    From keystone   with Apache License 2.0 5 votes vote down vote up
package keystoneml.utils

import java.awt.image.{DataBufferByte, BufferedImage}

object ImageConversions {
  
  def imageToBufferedImage(im: Image, scale: Boolean=false): BufferedImage = {
    val canvas = new BufferedImage(im.metadata.yDim, im.metadata.xDim, BufferedImage.TYPE_INT_RGB)

    //Scaling
    val scalef: Double => Int = if (scale) {
      val immin = im.toArray.min
      val immax = im.toArray.max
      d: Double => (255*(d-immin)/immax).toInt
    } else {
      d: Double => d.toInt
    }

    var x = 0
    while (x < im.metadata.xDim) {
      var y = 0
      while (y < im.metadata.yDim) {

        //Scale and pack into an rgb pixel.
        val chanArr = im.metadata.numChannels match {
          case 1 => Array(0,0,0)
          case 3 => Array(0,1,2)
        }

        val pixVals = chanArr.map(c => im.get(x, y, c)).map(scalef)
        val pix = (pixVals(0) << 16) | (pixVals(1) << 8) | pixVals(2)

        //Note, BufferedImage has opposite canvas coordinate system from us.
        //E.g. their x,y is our y,x.
        canvas.setRGB(y, x, pix)
        y += 1
      }
      x += 1
    }

    canvas
  }

} 
Example 15
Source File: Thumbnail.scala    From nescala   with GNU General Public License v2.0 5 votes vote down vote up
package com.owlandrews.nescala.helpers

import java.awt.Color
import java.awt.Dimension
import java.awt.geom.RoundRectangle2D
import java.awt.image.BufferedImage
import java.awt._

import scala.swing.Graphics2D
import scala.swing._

class Thumbnail(color: Color) {
  def Resize(image:Image) = {
    val thumbnail = image.getScaledInstance(Thumbnail.x, Thumbnail.y, Image.SCALE_SMOOTH)
    val arcs = new Dimension(10, 10)
    val output = new BufferedImage(Thumbnail.x,  Thumbnail.y, BufferedImage.TYPE_INT_ARGB)
    val outputGraphics = output.getGraphics.asInstanceOf[Graphics2D]
    outputGraphics.setComposite(AlphaComposite.Src)
    outputGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
    outputGraphics.setColor(color)
    outputGraphics.fill(new RoundRectangle2D.Float(0, 0, Thumbnail.x,  Thumbnail.y, arcs.width, arcs.height))
    outputGraphics.setComposite(AlphaComposite.SrcAtop)
    outputGraphics.drawImage(thumbnail, 0, 0, null)
    outputGraphics.dispose()
    output
  }
}

object Thumbnail {
  val x = 90
  val y = 120
  val padding = 25
} 
Example 16
Source File: PixelImageIO.scala    From scalismo-faces   with Apache License 2.0 5 votes vote down vote up
package scalismo.faces.io

import java.awt.image.BufferedImage
import java.io._

import javax.imageio.stream.MemoryCacheImageOutputStream
import javax.imageio.{IIOImage, ImageWriteParam}
import scalismo.faces.image.{BufferedImageConverter, PixelImage}

import scala.util.Try


object PixelImageIO {
  
  def writeJPEGToStream[Pixel](image: BufferedImage, outputStream: OutputStream, quality: Float): Try[Unit] = Try {
    val jpgWriter = javax.imageio.ImageIO.getImageWritersByFormatName("jpg").next()
    val jpgParams: ImageWriteParam = jpgWriter.getDefaultWriteParam
    jpgParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT)
    jpgParams.setCompressionQuality(quality.toFloat)
    val imageStream = new MemoryCacheImageOutputStream(outputStream)
    jpgWriter.setOutput(imageStream)
    jpgWriter.write(null, new IIOImage(image, null, null), jpgParams)
    jpgWriter.dispose()
  }
} 
Example 17
Source File: LandmarksDrawer.scala    From scalismo-faces   with Apache License 2.0 5 votes vote down vote up
package scalismo.faces.landmarks

import java.awt.image.BufferedImage
import java.awt.{Color, RenderingHints}

import scalismo.color.RGBA
import scalismo.faces.image.{BufferedImageConverter, PixelImage}

object LandmarksDrawer {
  
  def drawLandmarks(image: PixelImage[RGBA], landmarks: Iterable[TLMSLandmark2D], color: RGBA, size: Int): PixelImage[RGBA] = {
    val converter = implicitly[BufferedImageConverter[RGBA]]
    val bufImg: BufferedImage = converter.toBufferedImage(image)
    val g2d = bufImg.createGraphics()
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
    g2d.setPaint(new Color(color.r.toFloat, color.g.toFloat, color.b.toFloat, color.a.toFloat))
    for (lm <- landmarks)
      g2d.fillOval((lm.point.x - size / 2).toInt, (lm.point.y - size / 2).toInt, size, size)
    g2d.dispose()
    converter.toPixelImage(bufImg)
  }
} 
Example 18
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)
  }
} 
Example 19
Source File: BytesToBGRImg.scala    From BigDL   with Apache License 2.0 5 votes vote down vote up
package com.intel.analytics.bigdl.dataset.image

import java.awt.Color
import java.awt.image.{BufferedImage, DataBufferByte}
import java.nio.ByteBuffer

import com.intel.analytics.bigdl.dataset.{ByteRecord, Transformer}

import scala.collection.Iterator

object BytesToBGRImg {
  def apply(normalize: Float = 255f, resizeW : Int = -1, resizeH : Int = -1): BytesToBGRImg =
    new BytesToBGRImg(normalize, resizeW, resizeH)
}


class BytesToBGRImg(normalize: Float, resizeW : Int = -1, resizeH : Int = -1)
  extends Transformer[ByteRecord, LabeledBGRImage] {

  private val buffer = new LabeledBGRImage()

  override def apply(prev: Iterator[ByteRecord]): Iterator[LabeledBGRImage] = {
    prev.map(rawData => {
      buffer.copy(getImgData(rawData, resizeW, resizeH), normalize).setLabel(rawData.label)
    })
  }

  private def getImgData (record : ByteRecord, resizeW : Int, resizeH : Int)
  : Array[Byte] = {
    if (resizeW == -1) {
      return record.data
    } else {
      val rawData = record.data
      val imgBuffer = ByteBuffer.wrap(rawData)
      val width = imgBuffer.getInt
      val height = imgBuffer.getInt
      val bufferedImage : BufferedImage
      = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
      val outputImagePixelData = bufferedImage.getRaster.getDataBuffer
        .asInstanceOf[DataBufferByte].getData
      System.arraycopy(imgBuffer.array(), 8,
        outputImagePixelData, 0, outputImagePixelData.length)
      BGRImage.resizeImage(bufferedImage, resizeW, resizeH)
    }
  }
}