安卓手机如何将相机用作动态监测器

13

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

一个示例场景是这样的:设备放在架子上播放电影。如果有人出现在它前面,甚至不用触摸它 - 它就会切换电影。


1
让我补充一下,最终我没有做这件事,因为我的客户放弃了这个功能,而我自己也没有时间处理它。 - Yar
3个回答

23

2
项目描述:“Android代码通过比较两张图片来检测运动。” - ban-geoengineering

16

这里有一个教程,教你如何使用相机拍照。

如果你每秒拍一张照片,然后将其缩小到类似于8x8像素的大小,你可以轻松比较两张照片,查看是否发生了某些事情以触发你的操作。

你之所以要将其缩小,原因如下:

  1. 这样做会减少相机引入的噪声对图像的影响
  2. 这样做比对整个图像会更快速。

我喜欢你的回答。谢谢。只需要弄清楚如何使用前置摄像头。还有,如何缩放图像(做一个颜色平均值来创建缩放图像的一个像素?)。 - Yar
是的,就是这样,只需对源图像的多个像素求平均值即可。但请记住,平均值必须通过对多个像素进行求和来计算,这意味着数字可能会变得非常巨大。因此,请记得在计算中使用“long”。另外,仅对黑白图像进行操作可能已经足够了... - devsnd
链接无法使用,请您更新一下,好吗? - Noobification
最新的教程链接: https://newcircle.com/s/post/39/using__the_camera_api?page=3 - mostar

2

我解决了这个问题,每隔 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)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接