在Coding Train的COCOSSD教程中无法绘制检测物体包围框
COCOSSD检测结果无法绘制包围框与标签的问题解决
问题描述
我正在学习Coding Train的COCOSSD教程,已在画布上成功显示图片,控制台能正确输出检测物体的x、y坐标及宽高,但gotDetections函数中的绘图代码无法生成包围框与标签。已引入p5.js 1.5.0和ml5.js的CDN,尝试多种组合仍未解决问题。
原代码
let img; let detector; function preload() { img = loadImage("images/penguin.jpg"); detector = ml5.objectDetector("cocossd"); } function gotDetections(error, results) { if (error) { console.error(error); } console.log(results); for (let i = 0; i < results.length; i++) { let object = results[i]; console.log(object.x, object.y, object.width, object.height); stroke("green"); strokeWeight(4); noFill(); rect(object.x, object.y, object.width, object.height); noStroke(); fill(255); textSize(24); text(object.label, object.x + 10, object.y + 24); } } function setup() { createCanvas(640, 480); image(img, 0, 0, width, height); detector.detect(img, gotDetections); }
引入的CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script> <script src="https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>
问题原因
gotDetections是异步回调函数,当它执行时setup函数已经执行完毕。p5.js的画布渲染逻辑默认依赖draw循环,原代码中回调里的绘图操作发生在setup绘制图片之后,但此时画布不会自动刷新显示这些后续绘制的内容。
解决方案
提供两种可行的修改方式:
方式一:使用draw函数统一绘制
通过变量存储检测结果,在draw函数中完成图片和检测框的绘制,检测完成后触发一次重绘:
let img; let detector; let detections = []; // 存储检测结果 function preload() { img = loadImage("images/penguin.jpg"); detector = ml5.objectDetector("cocossd"); } function gotDetections(error, results) { if (error) { console.error(error); } detections = results; redraw(); // 触发draw函数重绘 } function setup() { createCanvas(640, 480); detector.detect(img, gotDetections); } function draw() { image(img, 0, 0, width, height); // 先绘制图片 // 遍历绘制检测框与标签 for (let i = 0; i < detections.length; i++) { let object = detections[i]; stroke("green"); strokeWeight(4); noFill(); rect(object.x, object.y, object.width, object.height); noStroke(); fill(255); textSize(24); text(object.label, object.x + 10, object.y + 24); } noLoop(); // 只绘制一次,避免重复刷新 }
方式二:在回调中重绘图片后绘制检测框
直接在gotDetections回调里先重绘图片,再绘制检测框,确保绘图操作覆盖当前画布:
let img; let detector; function preload() { img = loadImage("images/penguin.jpg"); detector = ml5.objectDetector("cocossd"); } function gotDetections(error, results) { if (error) { console.error(error); } console.log(results); image(img, 0, 0, width, height); // 先重绘图片 for (let i = 0; i < results.length; i++) { let object = results[i]; console.log(object.x, object.y, object.width, object.height); stroke("green"); strokeWeight(4); noFill(); rect(object.x, object.y, object.width, object.height); noStroke(); fill(255); textSize(24); text(object.label, object.x + 10, object.y + 24); } } function setup() { createCanvas(640, 480); detector.detect(img, gotDetections); }
内容的提问来源于stack exchange,提问作者Alex Liebhaber
相关产品推荐
相关产品推荐

