jeudi 23 juillet 2015

Javascript Canvas + Convolution Matrix. Conditional is always true

So, I'm trying to apply a convolution matrix to an image on a canvas.

For those of you who don't know how an image's data on the canvas is handled, it is handled through a large array of 8-bit integers. Each pixel is represented through 4 values in the array -- red, green, blue, and alpha. So that's why you may see a random 4 thrown in the code.

Anyway, my main problem comes with this conditional:

if ((i+x*4) % dY == i%dY)

where:

i == the location of the red value of the center pixel,

x == the displacement of pixels to select for the matrix,

dY == the amount of array values in a new row of pixels

The conditional always returns true in this context, but I want it to be true only if x extends beyond the left/right edges of the image.

Here is the entire function for context.

this.fire = function(imageData, value) {
    /*  function fire
            Applies this filter to the image.
        var imageData       an ImageData object that the filter is being applied.
        var value           the distance of the center to the edges of the matrix.
    */

    //Don't edit the data directly.
    var data = imageData.data.slice(0);

    //Used for sampling the image to avoid pixels already filtered.
    var pseudoData = data.slice(0);

    //The length of one row
    var dY = imageData.width * 4;

    //Distance from center to edges.
    var bigness = parseInt(value);

    //Generate a convolution matrix.
    var matrix = this.getMatrix(bigness*2+1);
    for (var i = 0; i < data.length; i+=4) {

        //Sum of the RGB channels that will later be applied to the pixel.
        var RGBSum = [0,0,0];

        //Sums all pixels in the matrix.
        for (var y = -1 * bigness; y <= bigness; y++) {

            //Select how many rows up
            var location = i + y * dY;

            //If out of bounds of the array, select the original row.
            if (location < 0||location >= data.length) {
                location = i;
            }
            for (var x = -1 * bigness; x <= bigness; x++) {

                //If adding x pixels doesn't change a row, shift the column selected.
                //Always firing true for some reason.
                if ((i+x*4) % dY == i%dY) {
                    //
                    //Testing to see which pixels are affected
                    //
                    data[i] = 255;
                    data[i+1] = 0;
                    data[i+2] = 0;
                    //
                    location += 4*x;
                }
                var matFact = matrix[y+bigness][x+bigness];
                RGBSum[0] += matFact * pseudoData[location];
                RGBSum[1] += matFact * pseudoData[location+1];
                RGBSum[2] += matFact * pseudoData[location+2];

            }
        }
        //Apply the RGB to the actual pixel
    }
    return data;
}

Aucun commentaire:

Enregistrer un commentaire