Skip to content

Instantly share code, notes, and snippets.

@shashir
Created February 22, 2016 20:50
Show Gist options
  • Save shashir/c0608cc7d75ed1e71252 to your computer and use it in GitHub Desktop.
Save shashir/c0608cc7d75ed1e71252 to your computer and use it in GitHub Desktop.
Generates a color histogram of an image to compute image distance Raw
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
case class Histogram(
resolution: Int,
pixels: Int,
histogram: Array[Array[Array[Int]]]
) {
def distance(that: Histogram): Double = {
require(this.resolution == that.resolution)
var sumOfSquares: Double = 0.
for (r <- 0 until resolution; g <- 0 until resolution; b <- 0 until resolution) {
val diff: Double =
this.histogram(r)(g)(b).toDouble / this.pixels - that.histogram(r)(g)(b).toDouble / that.pixels
sumOfSquares += (diff * diff)
}
return Math.sqrt(sumOfSquares)
}
override def toString(): String = {
val histogramString: String = histogram.map(_.map(_.toList).toList).toList.toString
return s"Histogram($resolution,$pixels,$histogramString)"
}
}
object Histogram {
val BYTE: Int = 256
def apply(file: String, resolution: Int): Histogram = {
apply(ImageIO.read(new File(file)), resolution)
}
def apply(image: BufferedImage, resolution: Int): Histogram = {
val bucketSize: Int = BYTE / resolution
val numPixels: Int = image.getHeight * image.getWidth
val pixels: Array[Int] = image.getRGB(
0,
0,
image.getWidth,
image.getHeight,
null,
0,
image.getWidth
)
val histogram: Array[Array[Array[Int]]] = Array.ofDim[Int](resolution, resolution, resolution)
for (i: Int <- pixels) {
val (_, r: Int, g: Int, b: Int) = pixel(i)
histogram(
Math.min(resolution - 1, r / bucketSize)
)(
Math.min(resolution - 1, g / bucketSize)
)(
Math.min(resolution - 1, b / bucketSize)
) += 1
}
return Histogram(resolution, numPixels, histogram)
}
def pixel(pixel: Int): (Int, Int, Int, Int) = {
return (
(pixel >> 24) & 0xff,
(pixel >> 16) & 0xff,
(pixel >> 8) & 0xff,
pixel & 0xff
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment