基于tensorflow.js和coco-ssd模型的实时目标检测网络应用程序
实现流程
- 访问用户的桌面录屏并且显示视频源(位置居中)。
- 对视频源进行实时目标检测。
- 在检测到的目标周围绘制边界框,并用它们的类别和检测置信度进行标记。
- 在视频源下方显示一个唯一检测到的目标列表,显示目标类别和首次检测到的时间。
- 确保每个目标类别只列出一次,不管它被检测到多少次。
- 使用2帧每秒的检测频率来平衡性能和响应性。
- 包括屏幕录制访问和模型加载的错误处理。
- 为应用程序设计一个干净、现代的外观,并具有响应式设计。
- 将所有必要的html、css和javascriptt包含在一个单一的自包含文件中。
- 为tensorflow.js和coco-ssd模型库使用cdn链接。 请提供完整可运行的html文件,其中包含内联css和javascript。
效果图
代码
<!doctype html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>实时目标检测</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>
<style>
body {
font-family: arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
}
#videocontainer {
position: relative;
margin-bottom: 20px;
}
#output {
position: absolute;
top: 0;
left: 0;
}
#detectionslist {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-width: 600px;
width: 100%;
}
#detectionslist h2 {
margin-top: 0;
}
#detectionslist ul {
list-style-type: none;
padding: 0;
}
#detectionslist li {
margin-bottom: 10px;
padding: 10px;
background-color: #f9f9f9;
border-radius: 4px;
}
#error {
color: red;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>实时目标检测</h1>
<div id="videocontainer">
<video id="video" width="640" height="480" autoplay muted></video>
<canvas id="output" width="640" height="480"></canvas>
</div>
<div id="detectionslist">
<h2>检测到的目标</h2>
<ul id="detectedobjects"></ul>
</div>
<div id="error"></div>
<script>
const video = document.getelementbyid('video');
const output = document.getelementbyid('output');
const ctx = output.getcontext('2d');
const detectedobjects = document.getelementbyid('detectedobjects');
const errordiv = document.getelementbyid('error');
let model;
let detections = new map();
async function setupcamera() {
try {
const stream = await navigator.mediadevices.getdisplaymedia({ video: true });
video.srcobject = stream;
return new promise((resolve) => {
video.onloadedmetadata = () => {
resolve(video);
};
});
} catch (error) {
errordiv.textcontent = '无法访问屏幕录制:' + error.message;
throw error;
}
}
async function loadmodel() {
try {
model = await cocossd.load();
} catch (error) {
errordiv.textcontent = '无法加载模型:' + error.message;
throw error;
}
}
async function detectobjects() {
try {
const predictions = await model.detect(video);
ctx.clearrect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawimage(video, 0, 0, ctx.canvas.width, ctx.canvas.height);
predictions.foreach(prediction => {
const [x, y, width, height] = prediction.bbox;
ctx.strokestyle = '#00ffff';
ctx.linewidth = 2;
ctx.strokerect(x, y, width, height);
ctx.fillstyle = '#00ffff';
ctx.font = '16px arial';
ctx.filltext(`${prediction.class} (${math.round(prediction.score * 100)}%)`, x, y > 10 ? y - 5 : 10);
if (!detections.has(prediction.class)) {
const timestamp = new date().tolocaletimestring();
detections.set(prediction.class, timestamp);
updatedetectionslist();
}
});
} catch (error) {
console.error('检测对象时出错:', error);
}
settimeout(detectobjects, 500); // 每2秒检测一次 (2 fps)
}
function updatedetectionslist() {
detectedobjects.innerhtml = '';
detections.foreach((timestamp, objectclass) => {
const li = document.createelement('li');
li.textcontent = `${objectclass} - 首次检测时间: ${timestamp}`;
detectedobjects.appendchild(li);
});
}
async function run() {
try {
await setupcamera();
await loadmodel();
detectobjects();
} catch (error) {
console.error('应用程序初始化失败:', error);
}
}
run();
</script>
</body>
</html>
发表评论