Skip to content

Instantly share code, notes, and snippets.

@ryohji
Created December 13, 2019 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryohji/b759ddc9f91ad6b54dff57f43444791d to your computer and use it in GitHub Desktop.
Save ryohji/b759ddc9f91ad6b54dff57f43444791d to your computer and use it in GitHub Desktop.
2 dimensional image processing (filter)
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