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 = land and 0 = water?
With some reading I figured out a way to loop through all the pixels in the image after converting the image to base64 using online Base64ImageEncoder.
With the following fiddle I am able to figure out if the pixel is water or land then change the pixel color, so the output is:
I feel that I am very close to getting exactly what I need. What do I need to do to change the main for-loop to instead save data inside of a Matrix?
JavaScript:
$(document).ready(function() {
$("#btnSubmit").click(function(){
GetBinary();
});
});
function GetBinary() {
var canvas = document.createElement("canvas");
canvas.width = imgElement.offsetWidth;
canvas.height = imgElement.offsetHeight;
var ctx = canvas.getContext("2d");
ctx.drawImage(imgElement,0,0);
var map = ctx.getImageData(0,0,canvas.width,canvas.height);
var imdata = map.data;
var r,g,b;
for(var p = 0, len = imdata.length; p < len; p+=4) {
r = imdata[p]
g = imdata[p+1];
b = imdata[p+2];
if ((r >= 164 && r <= 255) && (g >= 191 && g <= 229) && (b >= 220 && b <= 255)) {
// black = water
imdata[p] = 0;
imdata[p+1] = 0;
imdata[p+2] = 0;
} else {
// white = land
imdata[p] = 255;
imdata[p+1] = 255;
imdata[p+2] = 255;
}
}
ctx.putImageData(map,0,0);
imgElement.src = canvas.toDataURL();
}
Please note that I used a base64 image so we are not allowed to paste here because it is too long. Please my fiddle instead.
HTML:
<img id='myImage' src='base64 image data' />
<br />
<input id = "btnSubmit" type="button" value="Get Binary Image"/>