google-chrome - 为什么这个 P5.js 网络摄像头运动检测代码会导致我的浏览器崩溃?
问题描述
我不明白为什么这段代码不起作用。没有显示语法错误 - Chrome 开发控制台中也没有“错误”。
如果移动并且页面似乎在不停地加载(好像陷入循环),则不会显示黑色图像 - 相机上的灯也不亮。
我已经注释掉了代码部分,问题发生在循环阶段。(如果没有进行像素检查,我可以让相机显示图像)。
在控制台的用户消息中 - 它建议我:
p5.js 说: dist() 期待至少 4 个参数,但只收到 3 个。
正如您从代码中看到的那样 - 它确实具有正确数量的参数。
我相信浏览器会“崩溃”,因为控制台中的这些消息在崩溃之前有 10,000 多条 - 如果是这种情况:我该如何阻止它?
// Variable for capture device
var video;
// Previous Frame
var prevFrame;
// How different must a pixel be to be a "motion" pixel
var threshold = 50;
function setup() {
createCanvas(320, 240);
pixelDensity(1);
video = createCapture(VIDEO);
video.size(width, height);
video.hide();
// Create an empty image the same size as the video
prevFrame = createImage(video.width, video.height);
}
function draw() {
image(prevFrame, 0, 0);
loadPixels();
video.loadPixels();
prevFrame.loadPixels();
// Begin loop to walk through every pixel
for (var x = 0; x < video.width; x++) {
for (var y = 0; y < video.height; y++) {
// Step 1, what is the location into the array
var loc = (x + y * video.width) * 4;
// Step 2, what is the previous color
var r1 = prevFrame.pixels[loc];
var g1 = prevFrame.pixels[loc + 1];
var b1 = prevFrame.pixels[loc + 2];
// Step 3, what is the current color
var r2 = video.pixels[loc];
var g2 = video.pixels[loc + 1];
var b2 = video.pixels[loc + 2];
// Step 4, compare colors (previous vs. current)
var diff = dist(r1, g1, b1, r2, g2, b2);
// Step 5, How different are the colors?
// If the color at that pixel has changed, then there is motion at that pixel.
if (diff > threshold) {
// If motion, display black
pixels[loc] = 0;
pixels[loc+1] = 0;
pixels[loc+2] = 0;
pixels[loc+3] = 0;
} else {
// If not, display white
pixels[loc] = 255;
pixels[loc+1] = 255;
pixels[loc+2] = 255;
pixels[loc+3] = 255;
}
}
}
updatePixels();
// Save frame for the next cycle
//if (video.canvas) {
prevFrame.copy(video, 0, 0, video.width, video.height, 0, 0, video.width, video.height); // Before we read the new frame, we always save the previous frame for comparison!
//}
}
解决方案
推荐阅读
- javascript - 我正在为我的 ASP.NET MVC 程序使用 DataTables 插件。该表显示没有任何 CSS。为什么?
- php - 尝试将 html 元素设置为 google 趋势嵌入时出现 PHP 错误
- r - 如何更改 geom_dotplot 中的点颜色?
- javascript - 在 JavaScript 函数中调用时如何从对象函数返回值
- google-sheets - 谷歌表格从字符串单元格的开头去除单引号
- api - REST API 任务的最佳实践(不是 CRUD)
- sql - 如何在处理 0 案例时跨一对多关系按列计数和分组?
- c# - 如何在 C# XML 文档注释中为参数指定示例值?
- java - 如何从 Spring Security 身份验证中排除删除 url?
- laravel - Laravel 7 将 React.js 添加到没有 composer 的项目需要 laravel/ui?