java.awt.Color Scala Examples
The following examples show how to use java.awt.Color.
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: FancySlider.scala From scalismo-ui with GNU General Public License v3.0 | 5 votes |
package scalismo.ui.view.util import java.awt.Color import scala.swing.event.ValueChanged import scala.swing.{Label, Slider} class FancySlider extends Slider { // intended to be overwritten in subclasses if needed def formattedValue(sliderValue: Int): String = sliderValue.toString val minLabel: Label = new Label { foreground = Color.GRAY } val maxLabel: Label = new Label { foreground = Color.GRAY } val valueLabel: Label = new Label { foreground = Color.BLACK } protected def updateLabels(): Unit = { if (paintLabels) { val texts = Seq(min, max, value) map formattedValue val tuples = texts.zip(Seq(minLabel, maxLabel, valueLabel)) val needsUpdate = tuples.exists { case (v, l) => l.text != v } if (needsUpdate) { tuples.foreach { case (v, l) => l.text = v } labels = Seq((min, minLabel), (max, maxLabel), (value, valueLabel)).filter(_._2.visible).toMap } } } paintLabels = true reactions += { case ValueChanged(c) if c eq this => updateLabels() } }
Example 2
Source File: MyChart.scala From Apache-Spark-2x-Machine-Learning-Cookbook with MIT License | 5 votes |
package spark.ml.cookbook.chapter1 import java.awt.Color import org.apache.log4j.{Level, Logger} import org.apache.spark.sql.SparkSession import org.jfree.chart.plot.{PlotOrientation, XYPlot} import org.jfree.chart.{ChartFactory, ChartFrame, JFreeChart} import org.jfree.data.xy.{XYSeries, XYSeriesCollection} import scala.util.Random object MyChart { def show(chart: JFreeChart) { val frame = new ChartFrame("plot", chart) frame.pack() frame.setVisible(true) } def configurePlot(plot: XYPlot): Unit = { plot.setBackgroundPaint(Color.WHITE) plot.setDomainGridlinePaint(Color.BLACK) plot.setRangeGridlinePaint(Color.BLACK) plot.setOutlineVisible(false) } def main(args: Array[String]): Unit = { Logger.getLogger("org").setLevel(Level.ERROR) // setup SparkSession to use for interactions with Spark val spark = SparkSession .builder .master("local[*]") .appName("myChart") .config("spark.sql.warehouse.dir", ".") .getOrCreate() val data = spark.sparkContext.parallelize(Random.shuffle(1 to 15).zipWithIndex) data.foreach(println) val xy = new XYSeries("") data.collect().foreach{ case (y: Int, x: Int) => xy.add(x,y) } val dataset = new XYSeriesCollection(xy) val chart = ChartFactory.createXYLineChart( "MyChart", // chart title "x", // x axis label "y", // y axis label dataset, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips false // urls ) val plot = chart.getXYPlot() configurePlot(plot) show(chart) spark.stop() } }
Example 3
Source File: color_value.scala From libisabelle with Apache License 2.0 | 5 votes |
package isabelle import java.awt.Color import java.util.Locale object Color_Value { private var cache = Map.empty[String, Color] def parse(s: String): Color = { val i = java.lang.Long.parseLong(s, 16) val r = ((i >> 24) & 0xFF).toInt val g = ((i >> 16) & 0xFF).toInt val b = ((i >> 8) & 0xFF).toInt val a = (i & 0xFF).toInt new Color(r, g, b, a) } def print(c: Color): String = { val r = new java.lang.Integer(c.getRed) val g = new java.lang.Integer(c.getGreen) val b = new java.lang.Integer(c.getBlue) val a = new java.lang.Integer(c.getAlpha) Word.uppercase(String.format(Locale.ROOT, "%02x%02x%02x%02x", r, g, b, a)) } def apply(s: String): Color = synchronized { cache.get(s) match { case Some(c) => c case None => val c = parse(s) cache += (s -> c) c } } }
Example 4
Source File: Bencharts.scala From rtree2d with Apache License 2.0 | 5 votes |
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 5
Source File: package.scala From shapenet-viewer with MIT License | 5 votes |
package edu.stanford.graphics.shapenet import java.awt.Color package object colors { def getColor(id: Int, alpha: Float): Color = DefaultColorPalette.getColor(id, alpha) def getColor(id: Int): Color = DefaultColorPalette.getColor(id) def getColor(c: Color, alpha: Float): Color = { new Color(c.getRed, c.getGreen, c.getBlue, (alpha*255).toInt) } def toHex(c: Color): String = { val hexColor = "#%06X%02X".format((0xFFFFFF & c.getRGB), c.getAlpha) hexColor } }
Example 6
Source File: ColorPalette.scala From shapenet-viewer with MIT License | 5 votes |
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 7
Source File: Colors.scala From Scurses with MIT License | 5 votes |
package net.team2xh.scurses import java.awt.Color object Colors { // Color codes val DIM_BLACK = 0 val DIM_RED = 1 val DIM_GREEN = 2 val DIM_YELLOW = 3 val DIM_BLUE = 4 val DIM_MAGENTA = 5 val DIM_CYAN = 6 val DIM_WHITE = 7 val BRIGHT_BLACK = 8 val BRIGHT_RED = 9 val BRIGHT_GREEN = 10 val BRIGHT_YELLOW = 11 val BRIGHT_BLUE = 12 val BRIGHT_MAGENTA = 13 val BRIGHT_CYAN = 14 val BRIGHT_WHITE = 15 def fromName(name: String) = name match { case "black" => DIM_BLACK case "red" => BRIGHT_RED case "green" => BRIGHT_GREEN case "yellow" => BRIGHT_YELLOW case "blue" => BRIGHT_BLUE case "magenta" => BRIGHT_MAGENTA case "cyan" => BRIGHT_CYAN case "white" => BRIGHT_WHITE case "gray" => BRIGHT_BLACK } def fromRGB(color: (Int, Int, Int)): Int = { val distances = xtermRGB.map(distance(color, _)).zipWithIndex distances.minBy(_._1)._2 } def fromHex(hex: String): Int = fromRGB(hexToRGB(hex)) def fromRGBInt(int: Int): Int = { val color = new Color(int) fromRGB((color.getRed, color.getGreen, color.getBlue)) } private def hexToRGB(hex: String): (Int, Int, Int) = { val h = if (hex(0) == '#') hex.tail else hex (Integer.parseInt("" + h(0) + h(1), 16), Integer.parseInt("" + h(2) + h(3), 16), Integer.parseInt("" + h(4) + h(5), 16)) } private val xtermHex = Seq( "000000", "800000", "008000", "808000", "000080", "800080", "008080", "c0c0c0", "808080", "ff0000", "00ff00", "ffff00", "0000ff", "ff00ff", "00ffff", "ffffff", "000000", "00005f", "000087", "0000af", "0000d7", "0000ff", "005f00", "005f5f", "005f87", "005faf", "005fd7", "005fff", "008700", "00875f", "008787", "0087af", "0087d7", "0087ff", "00af00", "00af5f", "00af87", "00afaf", "00afd7", "00afff", "00d700", "00d75f", "00d787", "00d7af", "00d7d7", "00d7ff", "00ff00", "00ff5f", "00ff87", "00ffaf", "00ffd7", "00ffff", "5f0000", "5f005f", "5f0087", "5f00af", "5f00d7", "5f00ff", "5f5f00", "5f5f5f", "5f5f87", "5f5faf", "5f5fd7", "5f5fff", "5f8700", "5f875f", "5f8787", "5f87af", "5f87d7", "5f87ff", "5faf00", "5faf5f", "5faf87", "5fafaf", "5fafd7", "5fafff", "5fd700", "5fd75f", "5fd787", "5fd7af", "5fd7d7", "5fd7ff", "5fff00", "5fff5f", "5fff87", "5fffaf", "5fffd7", "5fffff", "870000", "87005f", "870087", "8700af", "8700d7", "8700ff", "875f00", "875f5f", "875f87", "875faf", "875fd7", "875fff", "878700", "87875f", "878787", "8787af", "8787d7", "8787ff", "87af00", "87af5f", "87af87", "87afaf", "87afd7", "87afff", "87d700", "87d75f", "87d787", "87d7af", "87d7d7", "87d7ff", "87ff00", "87ff5f", "87ff87", "87ffaf", "87ffd7", "87ffff", "af0000", "af005f", "af0087", "af00af", "af00d7", "af00ff", "af5f00", "af5f5f", "af5f87", "af5faf", "af5fd7", "af5fff", "af8700", "af875f", "af8787", "af87af", "af87d7", "af87ff", "afaf00", "afaf5f", "afaf87", "afafaf", "afafd7", "afafff", "afd700", "afd75f", "afd787", "afd7af", "afd7d7", "afd7ff", "afff00", "afff5f", "afff87", "afffaf", "afffd7", "afffff", "d70000", "d7005f", "d70087", "d700af", "d700d7", "d700ff", "d75f00", "d75f5f", "d75f87", "d75faf", "d75fd7", "d75fff", "d78700", "d7875f", "d78787", "d787af", "d787d7", "d787ff", "d7af00", "d7af5f", "d7af87", "d7afaf", "d7afd7", "d7afff", "d7d700", "d7d75f", "d7d787", "d7d7af", "d7d7d7", "d7d7ff", "d7ff00", "d7ff5f", "d7ff87", "d7ffaf", "d7ffd7", "d7ffff", "ff0000", "ff005f", "ff0087", "ff00af", "ff00d7", "ff00ff", "ff5f00", "ff5f5f", "ff5f87", "ff5faf", "ff5fd7", "ff5fff", "ff8700", "ff875f", "ff8787", "ff87af", "ff87d7", "ff87ff", "ffaf00", "ffaf5f", "ffaf87", "ffafaf", "ffafd7", "ffafff", "ffd700", "ffd75f", "ffd787", "ffd7af", "ffd7d7", "ffd7ff", "ffff00", "ffff5f", "ffff87", "ffffaf", "ffffd7", "ffffff", "080808", "121212", "1c1c1c", "262626", "303030", "3a3a3a", "444444", "4e4e4e", "585858", "606060", "666666", "767676", "808080", "8a8a8a", "949494", "9e9e9e", "a8a8a8", "b2b2b2", "bcbcbc", "c6c6c6", "d0d0d0", "dadada", "e4e4e4", "eeeeee") private val xtermRGB = xtermHex map hexToRGB private def distance(a: (Int, Int, Int), b: (Int, Int, Int)): Double = { val x = a._1 - b._1 val y = a._2 - b._2 val z = a._3 - b._3 math.sqrt(x*x + y*y + z*z) } }
Example 8
Source File: SelectedSignalPanel.scala From chisel-gui with BSD 3-Clause "New" or "Revised" License | 5 votes |
package visualizer.components import java.awt.{Color, Font} import scalaswingcontrib.tree.Tree import visualizer._ import visualizer.config.DrawMetrics import visualizer.models._ import scala.swing.BorderPanel.Position.Center import scala.swing._ import scala.swing.event._ class SelectedSignalPanel(dataModel: DataModel, selectedSignalModel: SelectedSignalModel, tree: Tree[GenericTreeNode]) extends BorderPanel { /////////////////////////////////////////////////////////////////////////// // View /////////////////////////////////////////////////////////////////////////// add(tree, Center) focusable = true def computeBounds(): Unit = { preferredSize = new Dimension(600, TreeHelper.viewableDepthFirstIterator(tree).size * DrawMetrics.WaveformVerticalSpacing) revalidate() } /////////////////////////////////////////////////////////////////////////// // Controller /////////////////////////////////////////////////////////////////////////// listenTo(selectedSignalModel) listenTo(keys, tree.keys) reactions += { case _: SignalsChanged => computeBounds() repaint() case _: WaveFormatChanged | _: CursorSet => repaint() case KeyReleased(_, Key.BackSpace, _, _) => selectedSignalModel.removeSelectedSignals(this, tree.selection.paths.iterator) } }
Example 9
Source File: DecoupledPainter.scala From chisel-gui with BSD 3-Clause "New" or "Revised" License | 5 votes |
package visualizer.painters import java.awt.{Color, Rectangle} import visualizer.config.DrawMetrics._ import visualizer.models._ import scala.swing.Graphics2D class DecoupledPainter(selectedSignalModel: SelectedSignalModel) extends Painter(selectedSignalModel) { def paintWaveform(g: Graphics2D, visibleRect: Rectangle, top: Int, node: GenericTreeNode, maxTimestamp: Long): Unit = { val startTimestamp = selectedSignalModel.xCoordinateToTimestamp(visibleRect.x) val minLastEndTimestamp = maxTimestamp.min(selectedSignalModel.xCoordinateToTimestamp(visibleRect.x + visibleRect.width)) def paintSignal(wave: Wave, startTimestamp: Long): Unit = { var index = wave.findStartIndex(startTimestamp) while (index < wave.length) { val left: Int = selectedSignalModel.timestampToXCoordinate(wave.start(index)) val right: Int = if (index < wave.length - 1 || selectedSignalModel.timeSieveOpt.isDefined) { selectedSignalModel.timestampToXCoordinate(wave.end(index)) } else { val lastTime = minLastEndTimestamp.max(wave.end(index)) selectedSignalModel.timestampToXCoordinate(lastTime) } val value = wave.value(index) drawSegment(g, left, right, top, value) index += 1 } } node match { case waveFormNode: WaveFormNode => waveFormNode.signal match { case decoupledSignalGroup: DecoupledSignalGroup => getWave(decoupledSignalGroup.name, startTimestamp).foreach { wave => paintSignal(wave, startTimestamp) } case validSignalGroup: ValidSignalGroup => getWave(validSignalGroup.name, startTimestamp).foreach { case wave if wave.nonEmpty => paintSignal(wave, startTimestamp) } } } } def drawSegment(g: Graphics2D, left: Int, right: Int, top: Int, state: BigInt): Unit = { state match { case DecoupledSignalGroup.Fired => g.setColor(FireColor) g.fillPolygon(Painter.hexagon(left, right, top)) case DecoupledSignalGroup.Ready => g.setColor(ReadySetColor) g.fillPolygon(Painter.hexagon(left, right, top)) case DecoupledSignalGroup.Valid => g.setColor(ValidSetColor) g.fillPolygon(Painter.hexagon(left, right, top)) case DecoupledSignalGroup.Busy => g.setColor(Color.gray) g.drawLine(left, top + WaveformHeight / 2, right, top + WaveformHeight / 2) case _ => g.setColor(Color.gray) g.drawLine(left, top + WaveformHeight / 2, right, top + WaveformHeight / 2) } } }
Example 10
Source File: DrawMetrics.scala From chisel-gui with BSD 3-Clause "New" or "Revised" License | 5 votes |
package visualizer.config import java.awt.Color object DrawMetrics { val Foo: Int = 5 val WaveformHeight: Int = 20 val WaveformVerticalGap: Int = 5 val WaveformVerticalSpacing: Int = WaveformHeight + 2 * WaveformVerticalGap val MinorTicksPerMajor: Int = 10 val TimescaleHeight: Int = 25 val MinorTickTop: Int = 18 val MinMinorTickHSpace: Int = 5 val MarkerNameXOffset: Int = 5 val MarkerNameYOffset: Int = -20 val toggleSelectedBg: Color = Color.darkGray val toggleUnselectedBg: Color = Color.lightGray val defaultWaveBackground: Color = new Color(240, 240, 240) val defautWaveSignalColor: Color = Color.black val defaultWaveCursorColor: Color = new Color(39, 223, 85) val defaultWaveMarkerColor: Color = Color.black val defaultWavGridColor: Color = new Color(200, 200, 255) val altWaveBackground: Color = Color.black val altWaveSignalColor: Color = Color.green val altWaveCursorColor: Color = Color.white val altWaveMarkerColor: Color = Color.yellow val altWavGridColor: Color = Color.lightGray val FireColor: Color = Color.red // new Color(152, 251, 152) val ReadySetColor: Color = new Color(255, 240, 106) val ValidSetColor: Color = new Color(255, 208, 98) }
Example 11
Source File: SuperpixelSuite.scala From mmlspark with MIT License | 5 votes |
// 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 12
Source File: Graphics2DRenderContextSpec.scala From evilplot with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 13
Source File: ColorParameterImpl.scala From chatoverflow with Eclipse Public License 2.0 | 5 votes |
package org.codeoverflow.chatoverflow.requirement.parameter import org.codeoverflow.chatoverflow.api.io.parameter.ColorParameter import org.codeoverflow.chatoverflow.registry.Impl import java.awt.Color @Impl(impl = classOf[ColorParameter]) class ColorParameterImpl extends ColorParameter { private var value: Color = null override def getType: Class[Color] = classOf[Color] override def serialize(): String = s"${value.getRed},${value.getGreen},${value.getBlue},${value.getAlpha}" override def get(): Color = value override def deserialize(value: String): Unit = { val hex3 = "^#([a-fA-F0-9]{6})$".r // Test if the value contains # and then 6 hexadecimal numbers val hex4 = "^#([a-fA-F0-9]{8})$".r // Test if the value contains # and then 8 hexadecimal numbers val int3 = "^(\\d+),(\\d+),(\\d+)$".r //Test if the value contains 3 ints val int4 = "^(\\d+),(\\d+),(\\d+),(\\d+)$".r //Test if the value contains 4 ints val float3 = "^(\\d+(?:\\.\\d+)?),(\\d+(?:\\.\\d+)?),(\\d+(?:\\.\\d+)?)$".r //Test if the value contains 3 floats val float4 = "^(\\d+(?:\\.\\d+)?),(\\d+(?:\\.\\d+)?),(\\d+(?:\\.\\d+)?),(\\d+(?:\\.\\d+)?)$".r //Test if the value contains 4 floats value match { case hex3(hex) => { set(new Color(Integer.valueOf(hex.substring(0, 2), 16), Integer.valueOf(hex.substring(2, 4), 16), Integer.valueOf(hex.substring(4, 6), 16))) } case hex4(hex) => set(new Color(Integer.valueOf(hex.substring(0, 2), 16), Integer.valueOf(hex.substring(2, 4), 16), Integer.valueOf(hex.substring(4, 6), 16), Integer.valueOf(hex.substring(6, 8), 16))) case int3(r, g, b) => set(new Color(r.toInt, g.toInt, b.toInt)) case int4(r, g, b, a) => set(new Color(r.toInt, g.toInt, b.toInt, a.toInt)) case float3(r, g, b) => set(new Color(r.toFloat, g.toFloat, b.toFloat)) case float4(r, g, b, a) => set(new Color(r.toFloat, g.toFloat, b.toFloat, a.toFloat)) case _ => throw new IllegalArgumentException("Could not convert String to color") } } override def set(value: Color): Unit = this.value = value }
Example 14
Source File: LSPReferencesAction.scala From intellij-lsp with Apache License 2.0 | 5 votes |
package com.github.gtache.lsp.actions import java.awt.Color import com.github.gtache.lsp.editor.EditorEventManager import com.intellij.codeInsight.hint.{HintManager, HintManagerImpl} import com.intellij.find.FindBundle import com.intellij.find.findUsages.{FindUsagesOptions, PsiElement2UsageTargetAdapter} import com.intellij.openapi.actionSystem.{AnActionEvent, CommonDataKeys} import com.intellij.openapi.editor.{Editor, LogicalPosition} import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElement import com.intellij.ui.LightweightHint import com.intellij.usageView.{UsageInfo, UsageViewUtil} import com.intellij.usages.impl.UsageViewManagerImpl import com.intellij.usages.{UsageInfo2UsageAdapter, UsageViewPresentation} import javax.swing.JLabel class LSPReferencesAction extends DumbAwareAction { override def actionPerformed(e: AnActionEvent): Unit = { val editor = e.getData(CommonDataKeys.EDITOR) if (editor != null) { val targets = EditorEventManager.forEditor(editor) .map(m => m.references(editor.getCaretModel.getCurrentCaret.getOffset, getOriginalElement = true, close = true)._1) .getOrElse(Seq()) .map(r => new PsiElement2UsageTargetAdapter(r)) showReferences(editor, targets, editor.getCaretModel.getCurrentCaret.getLogicalPosition) } } def forManagerAndOffset(manager: EditorEventManager, offset: Int): Unit = { val targets = manager.references(offset, getOriginalElement = true, close = true)._1.map(r => new PsiElement2UsageTargetAdapter(r)) val editor = manager.editor showReferences(editor, targets, editor.offsetToLogicalPosition(offset)) } def showReferences(editor: Editor, targets: Iterable[PsiElement2UsageTargetAdapter], logicalPosition: LogicalPosition): Unit = { if (targets.isEmpty) { val constraint: Short = HintManager.ABOVE val flags: Int = HintManager.HIDE_BY_ANY_KEY | HintManager.HIDE_BY_TEXT_CHANGE | HintManager.HIDE_BY_SCROLLING val label = new JLabel("No references found") label.setBackground(new Color(150, 0, 0)) val hint = new LightweightHint(label) val p = HintManagerImpl.getHintPosition(hint, editor, logicalPosition, constraint) HintManagerImpl.getInstanceImpl.showEditorHint(hint, editor, p, flags, 0, false, HintManagerImpl.createHintHint(editor, p, hint, constraint).setContentActive(false)) } else { val usageInfo = targets.map(ut => { val elem = ut.getElement new UsageInfo(elem, -1, -1, false) }) val presentation = createPresentation(targets.head.getElement, new FindUsagesOptions(editor.getProject), toOpenInNewTab = false) new UsageViewManagerImpl(editor.getProject).showUsages(Array(targets.head), usageInfo.map(ui => new UsageInfo2UsageAdapter(ui)).toArray, presentation) } } private def createPresentation(psiElement: PsiElement, options: FindUsagesOptions, toOpenInNewTab: Boolean) = { val presentation = new UsageViewPresentation val scopeString = options.searchScope.getDisplayName presentation.setScopeText(scopeString) val usagesString = options.generateUsagesString() presentation.setUsagesString(usagesString) val title = FindBundle.message("find.usages.of.element.in.scope.panel.title", usagesString, UsageViewUtil.getLongName(psiElement), scopeString) presentation.setTabText(title) presentation.setTabName(FindBundle.message("find.usages.of.element.tab.name", usagesString, UsageViewUtil.getShortName(psiElement))) presentation.setTargetsNodeText(StringUtil.capitalize(UsageViewUtil.getType(psiElement))) presentation.setOpenInNewTab(toOpenInNewTab) presentation } }
Example 15
Source File: BundledIcon.scala From scalismo-ui with GNU General Public License v3.0 | 5 votes |
package scalismo.ui.resources.icons import java.awt.{Color, Image} import javax.swing.ImageIcon import jiconfont.icons.{Elusive, Entypo, FontAwesome} import scalismo.ui.resources.icons.FontIcon.awesome import scalismo.ui.resources.icons.png.PngIconResource object BundledIcon { // This is an image (as opposed to an icon), because that's what Java Swing wants. // It's a 128x128 image that should hopefully be scaled according to the platform. lazy val AppIcon: Image = PngIconResource.load("app-icon.png").getImage lazy val Fallback: FontIcon = FontIcon.load(FontAwesome.BOLT) // this is relatively heavy, and seldomly needed, so we don't create a val. def Logo: ImageIcon = PngIconResource.load("logo.png") // basic icons lazy val Information: FontIcon = FontIcon.load(FontAwesome.INFO_CIRCLE, color = Color.BLUE.darker()) lazy val Warning: FontIcon = FontIcon.load(FontAwesome.EXCLAMATION_TRIANGLE, color = Color.ORANGE) lazy val Error: FontIcon = FontIcon.load(FontAwesome.TIMES_CIRCLE, color = Color.RED.darker()) lazy val Question: FontIcon = FontIcon.load(FontAwesome.QUESTION_CIRCLE, color = Color.BLUE.darker()) // toolbar, menu, or other general-purpose icons lazy val Center: FontIcon = FontIcon.load(FontAwesome.DOT_CIRCLE_O) lazy val Smiley: FontIcon = FontIcon.load(FontAwesome.SMILE_O) lazy val Reset: FontIcon = FontIcon.load(FontAwesome.UNDO) lazy val Screenshot: FontIcon = FontIcon.load(FontAwesome.CAMERA) lazy val Remove: FontIcon = FontIcon.load(awesome('\uf00d')) lazy val Save: FontIcon = FontIcon.load(awesome('\uf0c7')) lazy val Load: FontIcon = FontIcon.load(FontAwesome.FILE_O) lazy val Name: FontIcon = FontIcon.load(FontAwesome.FONT) lazy val Exit: FontIcon = FontIcon.load(Entypo.LOGOUT) lazy val Scale: FontIcon = FontIcon.load(Entypo.RESIZE_FULL) lazy val Perspective: FontIcon = FontIcon.load(Elusive.GLASSES) lazy val Visible: FontIcon = FontIcon.load(Elusive.EYE_OPEN) lazy val Invisible: FontIcon = FontIcon.load(Elusive.EYE_CLOSE) lazy val Background: FontIcon = FontIcon.load(Entypo.ADJUST) // general SceneNode icons lazy val Scene: FontIcon = FontIcon.load(FontAwesome.HOME) lazy val Group: FontIcon = FontIcon.load(FontAwesome.CUBES) lazy val FolderOpen: FontIcon = FontIcon.load(FontAwesome.FOLDER_OPEN_O) lazy val FolderClosed: FontIcon = FontIcon.load(FontAwesome.FOLDER_O) // particular SceneNode classes lazy val Mesh: FontIcon = FontIcon.load(FontAwesome.DIAMOND) lazy val PointCloud: FontIcon = FontIcon.load(awesome('\uf1e3')) lazy val Landmark: FontIcon = FontIcon.load(FontAwesome.CROSSHAIRS) lazy val Transformation: FontIcon = FontIcon.load(FontAwesome.ARROW_CIRCLE_RIGHT) lazy val Image: FontIcon = FontIcon.load(FontAwesome.PICTURE_O) lazy val VolumeMesh: FontIcon = FontIcon.load(FontAwesome.PAW) }
Example 16
Source File: BytesToBGRImg.scala From BigDL with Apache License 2.0 | 5 votes |
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) } } }
Example 17
Source File: LinkLabel.scala From scalismo-ui with GNU General Public License v3.0 | 5 votes |
package scalismo.ui.view.util import java.awt.event.{MouseAdapter, MouseEvent} import java.awt.{Color, Cursor, Desktop} import java.net.URI import javax.swing.Icon import scala.swing.Swing.EmptyIcon import scala.swing.{Alignment, Label} object LinkLabel { lazy val desktop: Option[Desktop] = { if (!Desktop.isDesktopSupported) None else { val desktop = Option(Desktop.getDesktop) if (desktop.nonEmpty && desktop.forall(_.isSupported(Desktop.Action.BROWSE))) desktop else None } } } class LinkLabel(text: String, uri: URI, icon: Icon = EmptyIcon, alignment: Alignment.Value = Alignment.Center, preventLinkStyle: Boolean = false, preventTooltip: Boolean = false) extends Label(text, icon, alignment) { if (!preventTooltip) { tooltip = uri.toString } // this will only kick in if the desktop can actually open links LinkLabel.desktop.foreach { d => if (!preventLinkStyle) { foreground = Color.BLUE.darker() // val attributes = font.getAttributes // attributes.asInstanceOf[java.util.Map[Object, Object]].put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON) // font = font.deriveFont(attributes) } cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) peer.addMouseListener(new MouseAdapter { override def mouseClicked(e: MouseEvent): Unit = { if (e.getClickCount == 1) { d.browse(uri) } } }) } }
Example 18
Source File: MultiLineLabel.scala From scalismo-ui with GNU General Public License v3.0 | 5 votes |
package scalismo.ui.view.util import java.awt.Color import javax.swing.{BorderFactory, UIManager} import scala.swing.TextArea class MultiLineLabel(text: String) extends TextArea(text) { peer.setLineWrap(true) peer.setWrapStyleWord(true) peer.setEditable(false) peer.setCursor(null) peer.setOpaque(false) peer.setFocusable(false) peer.setBackground(new Color(UIManager.getColor("control").getRGB)) private val hv = ScalableUI.scale(10) peer.setBorder(BorderFactory.createEmptyBorder(hv, hv, hv, hv)) }
Example 19
Source File: SimpleLandmarkingInteractor.scala From scalismo-ui with GNU General Public License v3.0 | 5 votes |
package scalismo.ui.control.interactor.landmark.simple import java.awt.event.MouseEvent import java.awt.{Color, Cursor} import javax.swing.SwingUtilities import scalismo.ui.control.interactor.Interactor.Verdict import scalismo.ui.control.interactor.Interactor.Verdict.Pass import scalismo.ui.control.interactor.{DefaultInteractor, Interactor, Recipe} import scalismo.ui.model.properties.Uncertainty import scalismo.ui.model.{LandmarkNode, SceneNode} import scalismo.ui.resources.icons.BundledIcon import scalismo.ui.view.ScalismoFrame import scala.swing.ToggleButton import scala.swing.event.ButtonClicked trait SimpleLandmarkingInteractorTrait extends Interactor { def defaultUncertainty: Uncertainty val landmarkingButton: ToggleButton = new ToggleButton { private val myIcon = BundledIcon.Landmark def updateUi(): Unit = { val onOff = if (selected) "ON" else "OFF" tooltip = s"Toggle landmarking (currently $onOff)" val iconColor = if (selected) Color.GREEN.darker else Color.DARK_GRAY icon = myIcon.colored(iconColor).standardSized() } reactions += { case ButtonClicked(_) => updateUi() } updateUi() } override def onActivated(frame: ScalismoFrame): Unit = { frame.toolbar.add(landmarkingButton) } override def onDeactivated(frame: ScalismoFrame): Unit = { frame.toolbar.remove(landmarkingButton) } override def mouseClicked(e: MouseEvent): Verdict = { if (landmarkingButton.selected && SwingUtilities.isLeftMouseButton(e)) { Recipe.AddLandmarkOnClick.mouseClicked(e, defaultUncertainty) } else { Pass } } // set the cursor to a crosshair if we're in landmarking mode override def mouseEntered(e: MouseEvent): Verdict = { val cursor = if (landmarkingButton.selected) Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR) else Cursor.getDefaultCursor e.canvas.setCursor(cursor) super.mouseEntered(e) } override def mouseMoved(e: MouseEvent): Verdict = { if (landmarkingButton.selected) { def exceptLandmarks(node: SceneNode) = node match { case _: LandmarkNode => false case _ => true } Recipe.HighlightOutlineOfPickableObject.mouseMoved(e, exceptLandmarks) } super.mouseMoved(e) } } object SimpleLandmarkingInteractor extends SimpleLandmarkingInteractorTrait with DefaultInteractor { override val defaultUncertainty: Uncertainty = Uncertainty.DefaultUncertainty override def mousePressed(e: MouseEvent): Verdict = Recipe.Block2DRotation.mousePressed(e) }
Example 20
Source File: BarChart.scala From Machine-Learning-with-Spark-Second-Edition with MIT License | 5 votes |
package org.sparksamples.linearregression import java.awt.{GradientPaint, Color} import org.jfree.chart.plot.PlotOrientation import org.jfree.chart.{ChartFactory, ChartPanel} import org.jfree.data.category.{CategoryDataset, DefaultCategoryDataset} import org.jfree.ui.{ApplicationFrame, RefineryUtilities} class BarChart(applicationTitle: String, chartTitle: String) extends ApplicationFrame(applicationTitle) { def exec(resultsMap: scala.collection.mutable.HashMap[String,String]) = { val results : Array[Double] = Array(0.0, 0.0) results(0) = 1.4 results(1) = 1.5 val barChart = ChartFactory.createBarChart( chartTitle, "Category", "Score", createDataset(resultsMap), PlotOrientation.VERTICAL, true, true, false); var renderer = barChart.getCategoryPlot.getRenderer val customColor = new Color(153,76,0); var gp0 = new GradientPaint( 0.0f, 0.0f, Color.DARK_GRAY, 0.0f, 0.0f, Color.DARK_GRAY ) val gp1 = new GradientPaint( 0.0f, 0.0f, customColor, 0.0f, 0.0f, customColor ) val gp2 = new GradientPaint( 0.0f, 0.0f, Color.red, 0.0f, 0.0f, Color.red ) renderer.setSeriesPaint(0, gp0) renderer.setSeriesPaint(1, customColor) //renderer.setSeriesPaint(2, gp2) val chartPanel = new ChartPanel(barChart); chartPanel.setPreferredSize(new java.awt.Dimension(560, 367)); setContentPane(chartPanel); } def createDataset (resultsMap: scala.collection.mutable.HashMap[String,String]) : CategoryDataset ={ val intercept_true = "true" val intercept_false = "false" val speed = "Speed" val rmsle = "RMSLE" val dataset = new DefaultCategoryDataset() dataset.addValue(resultsMap(intercept_true).toDouble, intercept_true, rmsle); dataset.addValue(resultsMap(intercept_true).toDouble, intercept_false, rmsle); return dataset; } } object BarChart { def main(args: Array[String]) { val chart = new BarChart("LinearRegressionWith SGD ", "Intercept") val resultsMap = new scala.collection.mutable.HashMap[String, String] resultsMap.put("true", "1.55") resultsMap.put("false", "1.56") chart.exec(resultsMap) chart.pack() RefineryUtilities.centerFrameOnScreen( chart ) chart.setVisible( true ) } }
Example 21
Source File: VisualLogger.scala From basel-face-pipeline with Apache License 2.0 | 5 votes |
package registration.utils import java.awt.Color import breeze.linalg.DenseVector import scalismo.geometry._3D import scalismo.mesh.TriangleMesh import scalismo.statisticalmodel.StatisticalMeshModel import scalismo.ui.api._ object VisualLogger { var ui : Option[ScalismoUI] = None//Some(ScalismoUI("Visual Logger")) val modelGroup = ui.map(_.createGroup("Model")) var modelView : Option[StatisticalMeshModelViewControls] = None val targetGroup = ui.map(_.createGroup("Target")) var targetMeshView : Option[TriangleMeshView] = None def showTargetMesh(targetMesh : TriangleMesh[_3D]) : Unit = { remove(targetMeshView) targetMeshView = show(VisualLogger.targetGroup, targetMesh, "target") targetMeshView.map(_.color = Color.RED) } def showStatisticalShapeModel(ssm : StatisticalMeshModel) : Unit = { removeModel(modelView) modelView = show(modelGroup, ssm, "gpmodel") modelView.map(_.meshView.opacity = 0.7) } def updateModelView(coeffs : DenseVector[Double]) : Unit = { if (modelView.isDefined) { modelView.get.shapeModelTransformationView.shapeTransformationView.coefficients = coeffs } } private def show[A](group : Option[Group], t : A, name : String)(implicit sic : ShowInScene[A]): Option[sic.View] = { for { ui <- ui g <- group } yield { ui.show(g, t, name) } } def remove[V <: ObjectView](view : Option[V]): Unit = { view.foreach(_.remove()) } def removeModel(view : Option[StatisticalMeshModelViewControls]): Unit = { for {v <- view} { v.meshView.remove() v.shapeModelTransformationView.remove() } } }
Example 22
Source File: MyMath.scala From Muse-CGH with MIT License | 5 votes |
package utilities import java.awt.Color def nearIndexOption(index: Int, size: Int, offset: Int): Option[Int] = { val ni = index + offset if(ni>=0 && ni<size) Some(ni) else None } def totalLength(points: IndexedSeq[Vec2]): Double = { var len = 0.0 var i = 0 while (i < points.length - 1) { len += (points(i+1)-points(i)).length i += 1 } len } case class MinimizationConfig(errorForStop: Double, maxIterations: Int, learningRate: Double = 0.1, gradientDelta: Double = 1e-2) case class MinimizationReport(iterations: Int, error: Double, lastDeltaError: Double) def minimize(f: IndexedSeq[Double] => Double, config: MinimizationConfig)(initParams: IndexedSeq[Double]): (MinimizationReport,IndexedSeq[Double]) = { def partialDerivative(params: IndexedSeq[Double] ,paramIndex: Int): Double = { val forward = f(params.updated(paramIndex, params(paramIndex)+ config.gradientDelta)) val backward = f(params.updated(paramIndex, params(paramIndex)- config.gradientDelta)) (forward - backward) / (2* config.gradientDelta) } var params = initParams var oldError = f(initParams) var deltaError = -1.0 for(i <- 0 until config.maxIterations){ params = params.indices.map{pIdx => params(pIdx) - partialDerivative(params, pIdx) * config.learningRate } val newError = f(params) deltaError = newError - oldError if(math.abs(deltaError) < config.errorForStop) { val report = MinimizationReport(i, newError, lastDeltaError = deltaError) return (report, params) } oldError = newError } (MinimizationReport(config.maxIterations, oldError, deltaError), params) } }
Example 23
Source File: MuseCharPainter.scala From Muse-CGH with MIT License | 5 votes |
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 24
Source File: AlloyUtility.scala From Electrodynamics with GNU Lesser General Public License v3.0 | 5 votes |
package com.calclavia.edx.core.resource.alloy import java.awt.Color import net.minecraft.item.ItemStack import resonantengine.lib.factory.resources.ResourceFactory import resonantengine.lib.utility.nbt.NBTUtility def mixedColor(materials: Map[String, Float]): Int = { val colorMap = materials.map(keyVal => (keyVal._1, new Color(ResourceFactory.getColor(keyVal._1)))) val averageRGB = colorMap .map(keyVal => (keyVal._2.getRed * materials(keyVal._1), keyVal._2.getGreen * materials(keyVal._1), keyVal._2.getBlue * materials(keyVal._1))) .foldLeft((0f, 0f, 0f))((b, a) => (a._1 + b._1, a._2 + b._2, a._3 + b._3)) return new Color(averageRGB._1.toInt, averageRGB._2.toInt, averageRGB._3.toInt).getRGB() } def mixedColor(materials: Seq[String]): Int = { val colors = materials.map(ResourceFactory.getColor).map(new Color(_)) val totalRGB = colors.map(c => (c.getRed, c.getGreen, c.getBlue)).foldLeft((0f, 0f, 0f))((b, a) => (a._1 + b._1, a._2 + b._2, a._3 + b._3)) val averageRGB = (totalRGB._1 / materials.size, totalRGB._2 / materials.size, totalRGB._3 / materials.size) return new Color(averageRGB._1.toInt, averageRGB._2.toInt, averageRGB._3.toInt).getRGB() } def setAlloy(itemStack: ItemStack, alloy: Alloy): ItemStack = { alloy.save(NBTUtility.getNBTTagCompound(itemStack)) itemStack } def getAlloy(itemStack: ItemStack) = new Alloy(NBTUtility.getNBTTagCompound(itemStack)) }
Example 25
Source File: Graph.scala From temperature-machine with Apache License 2.0 | 5 votes |
package bad.robot.temperature.rrd import java.awt.Color import bad.robot.temperature.rrd.RpnGenerator._ import bad.robot.temperature.rrd.RrdFile.MaxSensors import bad.robot.temperature.{FileOps, Files} import org.rrd4j.ConsolFun._ import org.rrd4j.core.RrdDb import org.rrd4j.graph.{RrdGraph, RrdGraphDef} import bad.robot.temperature.Files._ object Graph { private class CircularArray[T](array: Array[T]) { private var index = -1 def next: T = { if (index == array.length - 1) index = 0 else index = index + 1 array(index) } } private val colours = new CircularArray(Array( new Color(69, 114, 167), // #4572A7 san marino (blue) new Color(170, 70, 67), // #AA4643 roof terracotta (red) new Color(137, 165, 78), // #89A54E chelsea cucumber (green) new Color(128, 105, 155), // #80699B deluge (purple) new Color(61, 150, 174), // #3D96AE boston blue new Color(219, 132, 61), // #DB843D tree poppy (orange) new Color(146, 168, 205), // #92A8CD polo blue new Color(164, 125, 124), // #A47D7C opium new Color(181, 202, 146) // #B5CA92 sprout )) def create(from: Seconds, to: Seconds, hosts: List[Host], title: String) = { val graph = new RrdGraphDef() graph.setWidth(800) graph.setHeight(500) graph.setFilename(Files.path / s"temperature-${(to - from).toDays}-days.png") graph.setStartTime(from) graph.setEndTime(to) graph.setTitle(title) graph.setVerticalLabel("°C") val all = for { host <- hosts sensor <- 1 to MaxSensors } yield s"${host.name}-sensor-$sensor" val sensors = all.filter(new RrdDb(RrdFile.file).hasValuesFor) sensors.foreach(name => { graph.datasource(name, RrdFile.file, name, AVERAGE) graph.line(name, colours.next, name) }) graph.comment("\\l") graph.hrule(0, new Color(51, 153, 255), "Freezing") hosts.map(host => host -> sensors.filter(_.contains(host.name))).foreach({ case (_, Nil) => () case (host, sensor :: Nil) => graph.gprint(sensor, MIN, s"${host.name} min = %.2f%s °C") graph.gprint(sensor, MAX, s"${host.name} max = %.2f%s °C\\j") case (host, sensorsForHost) => graph.datasource(s"${host.name}-max", generateRpn(sensorsForHost, Max)) graph.datasource(s"${host.name}-min", generateRpn(sensorsForHost, Min)) graph.gprint(s"${host.name}-min", MIN, s"${host.name} min = %.2f%s °C") graph.gprint(s"${host.name}-max", MAX, s"${host.name} max = %.2f%s °C\\j") }) graph.setImageFormat("png") new RrdGraph(graph) } def transparent(color: Color): Color = { val rgb = color.getRGB val red = (rgb >> 16) & 0xFF val green = (rgb >> 8) & 0xFF val blue = rgb & 0xFF new Color(red, green, blue, 0x33) } }
Example 26
Source File: GrayscaleConverter.scala From Scala-Machine-Learning-Projects with MIT License | 5 votes |
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 27
Source File: Thumbnail.scala From nescala with GNU General Public License v2.0 | 5 votes |
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 28
Source File: LandmarksDrawer.scala From scalismo-faces with Apache License 2.0 | 5 votes |
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 29
Source File: Utils.scala From BigDL with Apache License 2.0 | 5 votes |
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) } }