Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to compare two different bitmap image and detect the different area in javascript?

I'm going to make a game that the user detects the different area of the two image. That two images has a few different area and looks all same, so the users should find out.

so I want to compare two different bitmap image and detect the different area.

does somebody can give me a hint? Do I have to use the canvas?

I'm making this game with HTML5, javascript.......

like image 470
user1505537 Avatar asked Dec 29 '25 13:12

user1505537


1 Answers

First, draw each image onto a canvas

var img1 = (your first image), 
    img2 = (your second image),
    ctx1 = document.createElement('canvas').getContext('2d'),
    ctx2 = document.createElement('canvas').getContext('2d');

ctx1.canvas.width = img1.width;
ctx2.canvas.width = img2.width;
ctx1.canvas.height = img1.height;
ctx2.canvas.height = img2.height;

ctx1.drawImage(img1, 0, 0);
ctx2.drawImage(img2, 0, 0);

Then, get the image data for each img

var data1 = ctx1.getImageData(0, 0, img1.width, img1.height);
var data2 = ctx2.getImageData(0, 0, img2.width, img2.height);

And finally, compare (this assumes img1 and img2 are the same dimensions)

var different = [];

for (var y=0; y<img1.height; y++){
    for (var x=0; x<img1.width; i++){
        var pos = (x * 4) + (y * (img.width * 4));
        for (var i=0; i<4; i++){
            if (data1[pos + i] != data2[pos + i]){
               different.push({x: x, y: y});
            }
        }
    }
}

This will give you an array of x, y coordinates of all pixels that are different between the two images.

like image 125
hobberwickey Avatar answered Dec 31 '25 03:12

hobberwickey