I have one function in my code to detect edges in a canvas but it's the slowest part of my code and is used everywhere. If I could just optimise this, my whole program would speed up considerably.
Maybe something better can be done with Em6?
Basically the function goes from the left until it finds a pixel colour greater (or less than) the colour value passed to the function. Then it gets the maximum or minimum of all the values which is the edge of whatever is inside the image.
Then it does the same for the top, the right the bottom to find all edges. Useful for cropping something within a canvas.
function getEdges(tempcanv, colour, which, condition) {
let ledge = [], redge = [], tedge = [], bedge = [];
const canvwidth = tempcanv.width, canvheight = tempcanv.height;
const contextd = tempcanv.getContext('2d');
for (let y = 0; y < canvheight; y++) {//left edge
for (let x = 0; x < canvwidth; x++) {
const data = contextd.getImageData(x, y, 1, 1).data;
if (condition(data[which], colour)) {
ledge.push(x);
break;
}
}
}
ledge = Math.min(...ledge);
const llim = ledge === 0 ? ledge : ledge - 1;
for (let x = llim; x < canvwidth; x++) {//top edge
for (let y = 0; y < canvheight; y++) {
const data = contextd.getImageData(x, y, 1, 1).data;
if (condition(data[which], colour)) {
tedge.push(y);
break;
}
}
}
tedge = Math.min(...tedge);
const tlim = tedge === 0 ? tedge : tedge - 1;
for (let y = tlim; y < canvheight; y++) {//right edge
for (let x = canvwidth - 1; x >= ledge; x--) {
const data = contextd.getImageData(x, y, 1, 1).data;
if (condition(data[which], colour)) {
redge.push(x);
break;
}
}
}
redge = Math.max(...redge);
for (let x = llim; x <= redge; x++) {//bottom edge
for (let y = canvheight - 1; y >= tedge; y--) {
const data = contextd.getImageData(x, y, 1, 1).data;
if (condition(data[which], colour)) {
bedge.push(y);
break;
}
}
}
return [ledge, tedge, redge + 1, Math.max(...bedge) + 1]
}
//(canvas passed, colour threshold, R,G or B, greater or less than)
getEdges(canvas, 180, 0, (a, b) => a > b))
My code does have some optimisation since as it finds an edge, the next edge check does not check the dead space already checked.
condition
can be seen in the function call at the bottom. \$\endgroup\$findCropBoxByColor()
? It finds the cropping box by color. \$\endgroup\$