Estoy usando Node.Js e intento dibujar líneas alrededor de partes de una imagen cada vez que se cumple una condición. Básicamente, estoy tratando de delinear objetos en una respuesta de imagen de una API. Tengo una respuesta proveniente de una API y cada vez que esa respuesta contiene "PALABRA", me gustaría dibujar dos líneas que encierran una parte de una imagen. Al final, me gustaría guardar todas las líneas dibujadas y exportar la imagen, ahora con las líneas dibujadas en ella.
Logré obtener la respuesta de la API, recorrer los objetos en la respuesta y verificar si los objetos coinciden con una condición de filtrado. Luego logré dibujar un conjunto de líneas, pero no puedo determinar cómo dibujar las líneas cada vez que se cumple la condición y guardar todos los dibujos resultantes. La imagen resultante solo tiene un único grupo de líneas dibujadas. Estoy usando el paquete de imágenes y Canvas.
// get image var ImageDATA = await getImage() // Get the height, width of the image const dimensions = sizeOf(ImageDATA.Body) const width = dimensions.width const height = dimensions.height console.log(ImageDATA.Body) console.log(width, height) try{ // Call API and log response const res = await client.detectDocumentText(params).promise(); // set the response as an image and get width and height var image = images(ImageDATA.Body).size(width, height) //console.log(res) res.Blocks.forEach(block => { if (block.BlockType.indexOf('WORD') > -1) { //console.log("Word Geometry Found."); console.log("FOUND POLYGONS") ctx.strokeStyle = 'rgba(0,0,0,0.5)'; console.log(block.Geometry.Polygon[0].X) ctx.beginPath(); ctx.lineTo(width * block.Geometry.Polygon[3].X, height * block.Geometry.Polygon[3].Y); ctx.moveTo(width * block.Geometry.Polygon[1].X, height * block.Geometry.Polygon[1].Y); ctx.lineTo(width * block.Geometry.Polygon[2].X, height * block.Geometry.Polygon[2].Y); ctx.stroke(); } console.log("-----") }) // render image // convert canvas to buffer var buffer = canvas.toBuffer("image/png"); // draw the buffer onto the image image.draw(images(buffer), 10, 10) // save image image.save("output.jpg"); } catch (err){ console.error(err);}Aquí hay una muestra de la matriz Polygon:
[ { X: 0.9775164723396301, Y: 0.985478401184082 }, { X: 0.9951508641242981, Y: 0.985478401184082 }, { X: 0.9951508641242981, Y: 0.9966437816619873 }, { X: 0.9775164723396301, Y: 0.9966437816619873 } ]Define el límite comenzando desde la parte superior izquierda y moviéndose en el sentido de las agujas del reloj.
Si alguien sabe como lograr esto, se lo agradeceria mucho. Muchas gracias de antemano.
Prueba esto :
ctx.strokeStyle = 'rgba(0,0,0,0.5)'; ctx.beginPath(); block.Geometry.Polygon.forEach(({X, Y}) => ctx.lineTo(width * X, height * Y) ); ctx.closePath(); ctx.stroke();Aquí hay un ejemplo de trabajo:
const boudingBoxes = [ { label: "Pen", polygon: [ {x: 0.60, y: 0.64}, {x: 0.83, y: 0.66}, {x: 0.82, y: 0.70}, {x: 0.60, y: 0.70}, ] }, { label: "Camera", polygon: [ {x: 0.72, y: 0.20}, {x: 0.93, y: 0.25}, {x: 0.88, y: 0.43}, {x: 0.71, y: 0.39}, ] }, ] init(); async function init() { const image = new Image(); image.crossOrigin = ""; await new Promise(res => { image.onload = res; image.src = "https://picsum.photos/id/180/600/400"; }); const [width, height] = [image.naturalWidth, image.naturalHeight]; const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); // Draw the image canvas.width = width; canvas.height = height; ctx.drawImage(image, 0, 0); // Start Drawing the bounding boxes ctx.fillStyle = "red" ctx.strokeStyle = "red"; boudingBoxes.forEach(bBox => { // label ctx.font = "13px Verdana"; ctx.fillText(bBox.label, width * bBox.polygon[0].x, height * bBox.polygon[0].y - 6); // Bounding box ctx.beginPath(); bBox.polygon.forEach(({x, y}) => ctx.lineTo(width * x, height * y) ); ctx.closePath(); ctx.stroke(); }); document.body.appendChild(canvas); } // TMP const p = document.querySelector("p"); window.onmousemove = (e) => { const x = e.clientX / 600; const y = e.clientY / 400; p.innerHTML = `x: ${x} <br/> y: ${y}`; } body { margin: 0 } p {position: absolute } <p></p>