I need a 2D binary representation of the following PNG image:
Can anyone provide a method or a source to convert PNG image above to a 2D array where 1 = lan
It looks like image data returns a single array of rgba components, you just have to break it up into rows. See http://jsfiddle.net/mendesjuan/wjn0dub7/1/
var currentInnerArray;
var zeroesAndOnes = [];
for(var p = 0, len = imdata.length; p < len; p+=4) {
r = imdata[p]
g = imdata[p+1];
b = imdata[p+2];
// Each line is the pixel width * 4, (rgba), start a newline
if (p % imdata.width * 4 === 0) {
currentInnerArray = [];
zeroesAndOnes.push(currentInnerArray);
}
if ((r >= 164 && r <= 255) && (g >= 191 && g <= 229) && (b >= 220 && b <= 255)) {
currentInnerArray.push(0);
// black = water
imdata[p] = 0;
imdata[p+1] = 0;
imdata[p+2] = 0;
} else {
currentInnerArray.push(1);
// white = land
imdata[p] = 255;
imdata[p+1] = 255;
imdata[p+2] = 255;
}
}
// zeroesAndOnes has your 2d array
Here's the relevant part if you want to access individual pixels as a 2D array
var w = canvas.width * 4;
var r,g,b;
for (var i=0; i<canvas.width * 4; i+=4) {
for (var j=0; j<canvas.height; j+=1) {
//console.log(j*w+i, j*w+i+1, j*w+i+2, j*w+i+3);
r = imdata[j*w+i]
g = imdata[j*w+i+1];
b = imdata[j*w+i+2];
if ((r >= 164 && r <= 255) &&
(g >= 191 && g <= 229) &&
(b >= 220 && b <= 255)) {
// blue = water
imdata[j*w+i] = 0;
imdata[j*w+i+1] = 0;
imdata[j*w+i+2] = 150;
} else {
// green = land
imdata[j*w+i] = 0;
imdata[j*w+i+1] = 120;
imdata[j*w+i+2] = 0;
}
}
}