Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package images
- import java.awt.Color
- import java.awt.image.BufferedImage
- object Processing {
- fun BufferedImage.getColor(x: Int, y: Int) = Color(getRGB(x, y))
- fun BufferedImage.setColor(x: Int, y: Int, color: Color) = setRGB(x, y, color.rgb)
- val BufferedImage.averageBrightness: Int
- get() {
- val grayed = grayed
- var sum = 0
- for (y in 0 until height)
- for (x in 0 until width)
- sum += grayed.getColor(x, y).red // any channel
- return sum / (width * height)
- }
- val BufferedImage.grayed: BufferedImage
- get() {
- val result = BufferedImage(width, height, type)
- for (y in 0 until height) {
- for (x in 0 until width) {
- val color = getColor(x, y)
- val gray = (0.21 * color.red + 0.71 * color.green + 0.07 * color.blue).toInt()
- val grayColor = Color(gray, gray, gray, color.alpha)
- result.setColor(x, y, grayColor)
- }
- }
- return result
- }
- private val BufferedImage.histogram: IntArray
- get() {
- val grayed = grayed
- val histogram = IntArray(256) { 0 }
- for (i in 0 until width) {
- for (j in 0 until height) {
- val brightness = grayed.getColor(i, j).red // any channel
- histogram[brightness]++
- }
- }
- return histogram
- }
- val BufferedImage.otsuThreshold: Int
- get() {
- val histogram = histogram
- val total = width * height
- val sum = histogram.sum()
- var sumB = 0f
- var wB = 0
- var varMax = 0f
- var threshold = 0
- for ((i, value) in histogram.withIndex()) {
- wB += value
- if (wB == 0)
- continue
- val wF = total - wB
- if (wF == 0)
- break
- sumB += (i * value)
- val mB = sumB / wB
- val mF = (sum - sumB) / wF
- val varBetween = wB.toFloat() * wF.toFloat() * (mB - mF) * (mB - mF)
- if (varBetween > varMax) {
- varMax = varBetween
- threshold = i
- }
- }
- return threshold
- }
- val BufferedImage.binarized: BufferedImage
- get() = binarize(averageBrightness)
- val BufferedImage.otsuBinarized: BufferedImage
- get() = binarize(otsuThreshold)
- fun BufferedImage.binarize(threshold: Int): BufferedImage {
- val grayed = grayed
- val binarized = BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY)
- for (y in 0 until height) {
- for (x in 0 until width) {
- val color = grayed.getColor(x, y)
- val brightness = color.red // any channel
- val value = if (brightness > threshold) 255 else 0
- val newColor = Color(value, value, value, color.alpha)
- binarized.setColor(x, y, newColor)
- }
- }
- return binarized
- }
- fun BufferedImage.resize(w: Int, h: Int): BufferedImage {
- val image = BufferedImage(w, h, type)
- val g = image.createGraphics()
- g.drawImage(this, 0, 0, w, h, null)
- g.dispose()
- return image
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement