I want to extract the pixels of an image that match some condition in backend (node.js). Something like https://onlinepngtools.com/extract-color-from-png . But for my case, it took about 5 – 6 seconds which is too slow for me. Any ideas to speed up?
// Get the image data
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// target color reference
const matchColor1 = { R: 100, G: 87, B: 34 };
const matchColor2 = { R: 32, G: 53, B: 81 };
// Loop through each pixel and extract the red color
for (let i = 0; i < imageData.data.length; i += 4) {
const R = imageData.data[i];
const G = imageData.data[i + 1];
const B = imageData.data[i + 2];
const color = { R, G, B };
// Check if the pixel is red (you can adjust the threshold as needed)
const match = diff(color, matchColor1) < 20 && R <= 120; // yellow label
const match2 = diff(color, matchColor2) < 28 && R < 120; // white label
const condition = match || match2;
if (condition) {
// Set the pixel to black
imageData.data[i] = 0; // R component
imageData.data[i + 1] = 0; // G component
imageData.data[i + 2] = 0; // B component
// imageData.data[i + 3] = 255; // Alpha component (optional, uncomment if needed)
} else {
// Set the pixel to white
imageData.data[i] = 255; // R component
imageData.data[i + 1] = 255; // G component
imageData.data[i + 2] = 255; // B component
// imageData.data[i + 3] = 255; // Alpha component (optional, uncomment if needed)
}
}
// Put the modified image data back onto the canvas
ctx.putImageData(imageData, 0, 0);