diff --git a/index.html b/index.html index 4e0655e..01c1673 100644 --- a/index.html +++ b/index.html @@ -47,6 +47,10 @@

How to use

  • Click to draw polygon points. Press enter to finish the polygon.
  • Coordinates

    +

    Load existing Polygon coordinates

    + + Load Polygon +

    Copy the points below, formatted as NumPy arrays, into your Python code.

    Copy Python to Clipboard diff --git a/script.js b/script.js index 5e068b3..14713a8 100644 --- a/script.js +++ b/script.js @@ -712,4 +712,89 @@ window.addEventListener('keydown', function(e) { if (e.key === 'f' || e.key === 'F') { toggleFullscreen(); } -}) \ No newline at end of file +}) + +document.querySelector('#loadCoordinates').addEventListener('click',function(e) { + e.preventDefault(); + + if(!img || !img.complete || img.naturalWidth === 0){ + alert("Please upload an image before loading points"); + } + + var inputVal = document.querySelector('#load-coordinates').value.trim(); + if(!inputVal) return; + + try{ + // Sanitize input + var sanitized = inputVal; + sanitized = sanitized.replace(/np\.array\(/g,'').replace(/\)/g,''); + + if(sanitized.startsWith('{') && sanitized.endsWith('}')){ + sanitized = '[' + sanitized.substring(1,sanitized.length-1)+']'; + } + sanitized = sanitized.replace(/,\s*([\]}])/g,'$1'); + var parsed = JSON.parse(sanitized); + + // convert object based points into array pairs + const objectToArray=(arr) => { + if(Array.isArray(arr)){ + if(arr.length >0 && typeof arr[0] === 'object' && arr[0] !== null && 'x' in arr[0]) { + return arr.map(point => [point.x,point.y]); + } + return arr.map(objectToArray); + } + return arr; + }; + parsed = objectToArray(parsed); + + if(parsed.length > 0 && Array.isArray(parsed[0]) && !Array.isArray(parsed[0][0])){ + parsed = [parsed]; + } + + if(!Array.isArray(parsed) || !Array.isArray(parsed[0]) ||!Array.isArray(parsed[0][0])){ + throw new Error("Invalid coordinate structure. Needs to be a list of polygons or single polygon."); + } + + // Detect and convert normalized points (0-1) to absolute pixels + var isNormalized = true; + for (var i=0;i 1 || parsed[i][j][1]>1){ + isNormalized = false; + break; + } + } + if(!isNormalized) break; + } + + if(isNormalized){ + for(var i=0; i