StuartDTO
StuartDTO

Reputation: 1061

Looping until find some pixels with the same colors in canvas

I'm trying to find a red color for example on a canvas, let's say I have a square painted on canvas, so I'd like to know the way to loop through that square and when I detect it get the x and y from now I have this :

var imgData = context.getImageData(face.x-1, face.y-1, 15+2, 15+2);
var pixels = imgData.data;

for (var i = 0; n = pixels.length, i < n; i += 4) {
    var red = pixels[i];
    var green = pixels[i+1];
    var blue = pixels[i+2];
    var alpha = pixels[i+3];
    //red color
    if(red == 255 && green == 0 && blue == 0){
         //fired when color is red
    }

Note: face.x and face.y is the X and Y to position an image

How can I do to loop the square let's say it's all black but 5 pixels that are red, I want to detect where is it and get the X and Y from the image in canvas

This is my Jsfiddle(I'm trying to find a red color for example on a canvas, let's say I have a square painted on canvas, so I'd like to know the way to loop through that square and when I detect it get the x and y from now I have this :

var imgData = context.getImageData(face.x-1, face.y-1, 15+2, 15+2);
var pixels = imgData.data;

for (var i = 0; n = pixels.length, i < n; i += 4) {
    var red = pixels[i];
    var green = pixels[i+1];
    var blue = pixels[i+2];
    var alpha = pixels[i+3];
    //red color
    if(red == 255 && green == 0 && blue == 0){
         //fired when color is red
    }

Note: face.x and face.y is the X and Y to position an image

How can I do to loop the square let's say it's all black but 5 pixels that are red, I want to detect where is it and get the X and Y from the image in canvas

I've put this

img.src = "https://i.imgur.com/x9uJH7a.gif";
imgCara.src = "https://i.imgur.com/vJJlYw2.png";

But that's only a test to show you what I'm trying to do (those img are the ones I'm using on my project) but I can't see it on jsfiddle...

I tried to position with

var w = cara.x-1 + ((i / 4) % (imgData.width));
var z = cara.y-1 + Math.floor((i /4)/(imgData.width));

But doesn't work.

Edit

I faced with this issue...

I've created this to save the x and y:

var xy={x:2,y:2};

Then I adapted your loop :

function findMatchingXY(R,G,B,tolerance){
// get the pixel data of the canvas
var data=context.getImageData(0,0,img.width,img.height).data;
// loop through all pixels
for(var y=0;y<img.width;y++){
    for(var x=0;x<img.height;x++){
        // find the pixel data from the data[] rgba array
        //     representing the pixel at [x,y]
        var n=(y*img.width+x)*4;
        // compare this pixel's color channels with the targets
        var matchesRedTarget=Math.abs(R-data[n])<tolerance;
        var matchesGreenTarget=Math.abs(G-data[n+1])<tolerance;
        var matchesBlueTarget=Math.abs(B-data[n+2])<tolerance;
        // does this pixel match the target
        if(data[n+3]>30 && matchesRedTarget
            && matchesGreenTarget && matchesBlueTarget){
            // return the x,y of the first matching pixel
            return({x:x,y:y});
        }
    }}
// no matching pixels found, return null
return(null);
}

and in chrome it says :

maze.js:26 Uncaught TypeError: Cannot read property 'x' of null

Upvotes: 2

Views: 1649

Answers (1)

markE
markE

Reputation: 105035

Since I'm only 51% sure I understand your question, I'll leave this example code and hope that it helps you either answer or clarify your question. The key part of the code is the findMatchingXY function -- which I annotated to show how it works.

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var size=15;
var $xy=$('#xy');
var targetRed=255;
var targetGreen=255;
var targetBlue=187;
var tolerance=5;

ctx.fillStyle='black';
ctx.fillRect(0,0,cw,ch);

$('#place').on('click',function(){
    // calc a random x,y and draw a 15x15 rect there
    var x=Math.random()*(cw-size);
    var y=Math.random()*(ch-size);
    ctx.fillStyle='black';
    ctx.fillRect(0,0,cw,ch);
    ctx.fillStyle='rgb('+targetRed+','+targetGreen+','+targetBlue+')';
    ctx.fillRect(x,y,15,15);
});

$('#find').on('click',function(){
    var xy=findMatchingXY();
    if(xy){
        $xy.text('Found the matching rect at x='+xy.x+', y='+xy.y);
    }else{
        $xy.text('There is no matching rect');
    }
});

$('#place').trigger('click');


function findMatchingXY(){
    // get the pixel data of the canvas
    var data=ctx.getImageData(0,0,cw,ch).data;
    // loop through all pixels
    for(var y=0;y<ch;y++){
    for(var x=0;x<cw;x++){
        // find the pixel data from the data[] rgba array
        //     representing the pixel at [x,y]
        var n=(y*cw+x)*4;
        // compare this pixel's color channels with the targets
        var matchesRedTarget=Math.abs(targetRed-data[n])<tolerance;
        var matchesGreenTarget=Math.abs(targetGreen-data[n+1])<tolerance;
        var matchesBlueTarget=Math.abs(targetBlue-data[n+2])<tolerance;
        // does this pixel match the target
        if(data[n+3]>30 && matchesRedTarget 
                && matchesGreenTarget && matchesBlueTarget){
            // return the x,y of the first matching pixel
            return({x:x,y:y});
        }
    }}
    // no matching pixels found, return null
    return(null);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='place'>Randomly place a rect</button>
<button id='find'>Find the randomly placed rect</button><br>
<h4 id='xy'>Place a target-color rect then find it.</h4>
<canvas id="canvas" width=300 height=100></canvas>

[ Addition: example using the maze image ]

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var $xy=$('#xy');
var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/mazeRed.png";
function start(){
    cw=canvas.width=img.width;
    ch=canvas.height=img.height;
    ctx.drawImage(img,0,0);
    var xy=findMatchingXY(255,47,47,10);
    if(xy){
        $xy.text('Found the matching pixel at x='+xy.x+', y='+xy.y);
    }else{
        $xy.text('There is no matching pixel');
    }    
}


function findMatchingXY(targetRed,targetGreen,targetBlue,tolerance){
    // get the pixel data of the canvas
    var data=ctx.getImageData(0,0,cw,ch).data;
    // loop through all pixels
    for(var y=0;y<ch;y++){
    for(var x=0;x<cw;x++){
        // find the pixel data from the data[] rgba array
        //     representing the pixel at [x,y]
        var n=(y*cw+x)*4;
        // compare this pixel's color channels with the targets
        var matchesRedTarget=Math.abs(targetRed-data[n])<tolerance;
        var matchesGreenTarget=Math.abs(targetGreen-data[n+1])<tolerance;
        var matchesBlueTarget=Math.abs(targetBlue-data[n+2])<tolerance;
        // does this pixel match the target
        if(data[n+3]>30 && matchesRedTarget 
                && matchesGreenTarget && matchesBlueTarget){
            // return the x,y of the first matching pixel
            return({x:x,y:y});
        }
    }}
    // no matching pixels found, return null
    return(null);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4 id='xy'>Finding red line in maze</h4><br>
<canvas id="canvas" width=300 height=100></canvas>

Upvotes: 3

Related Questions