如何使用前置摄像头和Android SDK实现简单的运动检测器?
一个示例场景是这样的:设备放在架子上播放电影。如果有人出现在它前面,甚至不用触摸它 - 它就会切换电影。
这是我为Android开发的开源移动检测应用。
这里有一个教程,教你如何使用相机拍照。
如果你每秒拍一张照片,然后将其缩小到类似于8x8像素的大小,你可以轻松比较两张照片,查看是否发生了某些事情以触发你的操作。
你之所以要将其缩小,原因如下:
我解决了这个问题,每隔 n
秒拍照并将其缩放为 10*10
像素,然后找到它们之间的差异。以下是 kotlin
实现:
private fun detectMotion(bitmap1: Bitmap, bitmap2: Bitmap) {
val difference =
getDifferencePercent(bitmap1.apply { scale(16, 12) }, bitmap2.apply { scale(16, 12) })
if (difference > 10) { // customize accuracy
// motion detected
}
}
private fun getDifferencePercent(img1: Bitmap, img2: Bitmap): Double {
if (img1.width != img2.width || img1.height != img2.height) {
val f = "(%d,%d) vs. (%d,%d)".format(img1.width, img1.height, img2.width, img2.height)
throw IllegalArgumentException("Images must have the same dimensions: $f")
}
var diff = 0L
for (y in 0 until img1.height) {
for (x in 0 until img1.width) {
diff += pixelDiff(img1.getPixel(x, y), img2.getPixel(x, y))
}
}
val maxDiff = 3L * 255 * img1.width * img1.height
return 100.0 * diff / maxDiff
}
private fun pixelDiff(rgb1: Int, rgb2: Int): Int {
val r1 = (rgb1 shr 16) and 0xff
val g1 = (rgb1 shr 8) and 0xff
val b1 = rgb1 and 0xff
val r2 = (rgb2 shr 16) and 0xff
val g2 = (rgb2 shr 8) and 0xff
val b2 = rgb2 and 0xff
return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2)
}