In my project, I am utilizing openCV.js for detecting contours in an image. Once the contours are identified, I proceed to implement certain filters and simplification techniques on these contours. Subsequently, I draw them as paths within an SVG for plotting purposes with a pen plotter. The issue I am currently facing lies in filtering out points from the generated array that fall between the boundaries of the SVG and the specified margin. While a clipping path could address this visually, it does not solve the underlying problem. What I require is for the actual paths to exclude these points so that they are not drawn by the pen plotter.
// Extract contour points and add to array
let points = [];
for (let j = 0; j < contours.size(); ++j) {
const ci = contours.get(j);
points[j] = [];
for (let k = 0; k < ci.data32S.length; k += 2) {
let p = [];
p[0] = parseInt(ci.data32S[k]);
p[1] = parseInt(ci.data32S[k + 1]);
points[j].push(p);
}
}
// Filter out contours with fewer than minNumPointsInContour
let fPoints = points.filter(function (element) {
return element.length >= minNumPointsInContour;
});
// Filter out points falling between margin and SVG edge (PROBLEMATIC AREA)
let mFPoints = fPoints.filter(
(element) => element[0] >= marginSlider.value
);
// Simplify points before drawing
let sFPoints = [];
mFPoints.forEach((element) => {
let simplifiedPoints = simplify(element, toleranceSlider.value, true);
sFPoints.push(simplifiedPoints);
});
The critical section of concern is
let mFPoints = fPoints.filter((element) => element[0] >= marginSlider.value);
. Currently, this code snippet checks only the x-value of each element in the array against the margin value. However, I need to assess four conditions instead of one.
As the fPoints
array is nested and contains point data, it is structured like [[0,0],[10,10],[10,20],etc]
. At this stage, the output appears as follows:
My objective is to filter the fPoints
array to include points where:
- x-value (
fPoints[0]
) exceeds the margin - x-value (
fPoints[0]
) is less than SVG width - margin - y-value (
fPoints[1]
) surpasses the margin - y-value (
fPoints[1]
) is below SVG height - margin
I find the challenge of evaluating two different values within a nested array quite perplexing.
If more details are needed, you can review the full code here.