write a program that adds salt and pepper noise to an image. in this case, the input variables of your program should be the probabilities pa and pb of the salt and pepper noise components. in javascript

Here is a sample program in JavaScript that takes an image as input and applies salt and pepper noise using probability pa and pb respectively.

index.tsx
function addSaltAndPepperNoise(imgData, pa, pb) {
    var w = imgData.width;
    var h = imgData.height;
    var data = imgData.data;

    var amount = pa + pb;

    for (var i = 0; i < data.length; i += 4) {
        var r = Math.random();

        if (r < pa) {
            // add salt
            data[i] = 255;
            data[i+1] = 255;
            data[i+2] = 255;
        } else if (r < amount) {
            // add pepper
            data[i] = 0;
            data[i+1] = 0;
            data[i+2] = 0;
        }
    }

    return imgData;
}
549 chars
26 lines

This function takes an imgData object (which has the width, height and data properties of the image), as well as the probabilities pa and pb for salt and pepper noise respectively.

For each pixel in the image, a random number is generated between 0 and 1. If this number is less than pa, then the pixel is set to white (255) to simulate salt noise. If the number is less than amount (which is the sum of pa and pb), but greater than pa, then the pixel is set to black (0) to simulate pepper noise. If the number is greater than amount, then the pixel is left unchanged.

Finally, the function returns the modified imgData object.

related categories

gistlibby LogSnag