要解决无法读取从 Flask 发送到 JavaScript 的对象 BoundingPoly
的问题,我们需要确保数据在前后端之间的传输是正确的,并且在 JavaScript 中正确解析和使用这些数据。以下是详细的步骤和示例代码:
BoundingPoly
是一个表示边界框的多边形对象,通常用于计算机视觉任务中,如目标检测。它包含一系列的顶点坐标,这些坐标定义了边界框的形状。
首先,确保 Flask 端正确地发送 BoundingPoly
对象。假设 BoundingPoly
是一个包含顶点坐标的列表。
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/get_bounding_poly', methods=['GET'])
def get_bounding_poly():
bounding_poly = {
"vertices": [
{"x": 100, "y": 100},
{"x": 200, "y": 100},
{"x": 200, "y": 200},
{"x": 100, "y": 200}
]
}
return jsonify(bounding_poly)
if __name__ == '__main__':
app.run(debug=True)
在 HTML 中,使用 JavaScript 获取并解析这个对象,然后在图像上绘制边界框。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Draw Bounding Poly</title>
<style>
#image {
width: 500px;
height: auto;
}
</style>
</head>
<body>
<img id="image" src="path_to_your_image.jpg" alt="Image">
<script>
async function fetchBoundingPoly() {
const response = await fetch('/get_bounding_poly');
const data = await response.json();
return data.vertices;
}
function drawBoundingPoly(vertices) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('image');
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
ctx.beginPath();
ctx.moveTo(vertices[0].x, vertices[0].y);
for (let i = 1; i < vertices.length; i++) {
ctx.lineTo(vertices[i].x, vertices[i].y);
}
ctx.closePath();
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.stroke();
document.body.appendChild(canvas);
}
fetchBoundingPoly().then(drawBoundingPoly);
</script>
</body>
</html>
通过以上步骤,你应该能够成功地在 HTML 中读取并使用从 Flask 发送的 BoundingPoly
对象,并在图像上绘制出边界框。
领取专属 10元无门槛券
手把手带您无忧上云