Created
December 13, 2019 08:59
-
-
Save ryohji/b759ddc9f91ad6b54dff57f43444791d to your computer and use it in GitHub Desktop.
2 dimensional image processing (filter)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object ImageProcessing { | |
fun smoothing(stride: Int, buffer: ByteArray): ByteArray = | |
buffer.toIntList() | |
.convolution(stride) | |
.map { (it / 9).toByte() } | |
.toByteArray() | |
fun sharpen(stride: Int, buffer: ByteArray): ByteArray = | |
buffer.toIntList() | |
.let { it.amplify(10).zip(it.convolution(stride)) { x, y -> x - y } } | |
.map { it.toByte() } | |
.toByteArray() | |
private fun List<Int>.convolution(stride: Int): List<Int> = | |
chunked(stride) | |
.map { | |
it.zip(it.take(1) + it) { x, y -> x + y } | |
.zip(it.drop(1) + it.takeLast(1)) { x, y -> x + y } | |
} | |
.let { | |
it.zip(it.take(1) + it) { a, b -> a.zip(b) { x, y -> x + y } } | |
.zip(it.drop(1) + it.takeLast(1)) { a, b -> a.zip(b) { x, y -> x + y } } | |
} | |
.flatten() | |
private fun List<Int>.amplify(c: Int) = map { it * c } | |
private fun ByteArray.toIntList() = toList().map { (256 + it) and 255 } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment