13

如何使用前置摄像头和 Android SDK 实现一个简单的运动检测器?

一个示例场景是这样的:设备站在支架上并播放电影。如果一个人出现在它面前,甚至没有触摸它——它就会改变电影。

4

3 回答 3

22

这是我的 Android 开源运动检测应用程序。

https://github.com/phishman3579/android-motion-detection

于 2012-10-09T00:27:30.647 回答
15

这是一个关于如何使用相机拍照的教程。

如果您每秒拍摄一张照片,然后将其缩小到 8x8 像素,您可以轻松比较两张照片并找出是否发生了什么事情,从而触发您的行动。

你应该缩小它的原因如下:

  1. 它不易出错,容易受到相机引入的噪音的影响
  2. 这将比对整个图像进行比较快得多
于 2012-03-19T17:04:43.407 回答
0

我解决了每秒拍照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)
}
于 2019-09-17T17:00:51.440 回答