Skip to content

Instantly share code, notes, and snippets.

View kiwiandroiddev's full-sized avatar

Matt Clarke kiwiandroiddev

  • Auckland, New Zealand
View GitHub Profile
@kiwiandroiddev
kiwiandroiddev / BigEndianBits.kt
Created February 28, 2020 22:56
Kotlin function to convert a list of bits (booleans) with big-endian ordering to an integer
/**
* Converts a list of bits (booleans) with big-endian ordering to its corresponding
* integer.
*/
fun List<Boolean>.bigEndianBitsToInt(): Int {
return reversed().foldIndexed(initial = 0) { bitNo: Int, output: Int, bit: Boolean ->
output or (bit.toInt() shl bitNo)
}
}
@kiwiandroiddev
kiwiandroiddev / loadOpenCvImage.kt
Created April 5, 2020 01:46
Decode an Android test resource image as an OpenCV Mat
/**
* Uses OpenCV to decode an image that is an android test resource i.e.
* a file from `src/androidTest/resources`.
* Note that the resulting Mat will be empty if there was a problem loading the file.
*/
private fun loadOpenCvImage(testResourceFilename: String): Mat {
val bytes: ByteArray = javaClass.classLoader!!.getResource(testResourceFilename).readBytes()
val matOfByte = MatOfByte().apply { fromList(bytes.toList()) }
return Imgcodecs.imdecode(matOfByte, CV_LOAD_IMAGE_COLOR)
}
@kiwiandroiddev
kiwiandroiddev / normalize.kt
Created October 15, 2020 04:28
Kotlin function to remove duplicate consecutive elements in a list, up to maxN duplicate consecutive elements
/**
* Removes duplicate consecutive elements in a list, up to maxN duplicate consecutive elements
* per group.
* Ex. where maxN = 2:
* [0, 0, 1, 2, 2, 4, 4, 4, 4] => [0, 1, 2, 4, 4]
*/
fun <T> List<T>.normalize(maxN: Int): List<T> {
var nextIndexToConsider = 0
return windowed(size = maxN, step = 1, partialWindows = true)
@kiwiandroiddev
kiwiandroiddev / RxScreenCaptureSource.kt
Created December 15, 2020 00:33
Returns an Observable stream of screen grabs using java.awt.Robot. Uses multiple threads to get a somewhat reasonable FPS as per https://github.com/bahusvel/JavaScreenCapture
fun getScreenCaptureSource(
screenRectangle: Rectangle,
numThreads: Int = 6,
fpsPerThread: Int = 8,
robot: Robot = Robot()
): Observable<BufferedImage> {
val periodPerThreadMs: Long = 1000 / fpsPerThread.toLong()
val perThreadOffsetMs: Long = periodPerThreadMs / numThreads
val sources = (0 until numThreads).map { i ->