xxxxxxxxxx
111
let img;
let contourPoints = [];
function preload() {
img = loadImage('australia.jpg');
}
function setup() {
createCanvas(500, 500);
background(50);
image(img, 0, 0, width, height);
loadPixels();
// Moore neighborhood offsets (clockwise from top-left)
const offsets = [
[-1, -1], [0, -1], [1, -1],
[1, 0], [1, 1], [0, 1],
[-1, 1], [-1, 0]
];
// Find starting point (first black pixel)
let startX = -1, startY = -1;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
let idx = (y * width + x) * 4;
if (pixels[idx] < 128) {
startX = x;
startY = y;
console.log("Found start at:", x, y);
break;
}
}
if (startX !== -1) break;
}
if (startX !== -1) {
// Initialize with starting point
let currentX = startX;
let currentY = startY;
contourPoints.push({x: currentX, y: currentY});
// Start by looking left of the first point
let backtrackX = startX - 1;
let backtrackY = startY;
while (true) {
// Find the backtrack offset index
let backtrackOffsetIndex = -1;
let backtrackDX = backtrackX - currentX;
let backtrackDY = backtrackY - currentY;
for (let i = 0; i < offsets.length; i++) {
if (offsets[i][0] === backtrackDX && offsets[i][1] === backtrackDY) {
backtrackOffsetIndex = i;
break;
}
}
let found = false;
let prevCheckX = backtrackX;
let prevCheckY = backtrackY;
// Search clockwise starting from the next position after backtrack
for (let i = 0; i < 7; i++) {
let checkIndex = (backtrackOffsetIndex + 1 + i) % 8;
let checkX = currentX + offsets[checkIndex][0];
let checkY = currentY + offsets[checkIndex][1];
if (checkX >= 0 && checkX < width && checkY >= 0 && checkY < height) {
let idx = (checkY * width + checkX) * 4;
if (pixels[idx] < 128) {
// Found next boundary pixel
backtrackX = currentX;
backtrackY = currentY;
currentX = checkX;
currentY = checkY;
contourPoints.push({x: currentX, y: currentY});
found = true;
break;
}
}
prevCheckX = checkX;
prevCheckY = checkY;
}
if (!found) break;
// Check if we're back at start
if (currentX === startX && currentY === startY && contourPoints.length > 2) {
contourPoints.pop(); // Remove duplicate end point
break;
}
}
}
// Draw the contour
stroke(255, 0, 0);
strokeWeight(2);
noFill();
beginShape();
for (let pt of contourPoints) {
vertex(pt.x, pt.y);
}
endShape(CLOSE);
console.log("Found", contourPoints.length, "points");
}
function draw() {
// No continuous drawing needed
}