Skip to content

Instantly share code, notes, and snippets.

@kjunichi
Created October 3, 2012 05:20
Show Gist options
  • Save kjunichi/3825172 to your computer and use it in GitHub Desktop.
Save kjunichi/3825172 to your computer and use it in GitHub Desktop.
face detect node.jsで顔検出

Source code.

var fs = require('fs');
var face_detect = require('face-detect');
 
var Canvas = require('canvas')
, Image = Canvas.Image;
 
var gNum = 0;
var gFaceDetect = false;
function detectFace(filepath) {
 
    fs.readFile(filepath, function(err, squid){
    if (err) throw err;
    var img = new Image;
    img.src = squid;
    var canvas = new Canvas(img.width, img.height);
    var ctx = canvas.getContext('2d');
     
    ctx.drawImage(img, 0,0,img.width,img.height);
     
    var result = face_detect.detect_objects({ "canvas" :
                          face_detect.grayscale(canvas),
                          //"cascade":cascade,
                          "interval" : 5,
                          "min_neighbors" : 1 });
     
    if(result.length > 0) {
        console.log(filepath  + ' Found ' + result.length  + ' faces.');
        gFaceDetect = true;
    }
    for (var i = 0; i < result.length; i++){
        var face =  result[i];
        console.log(face);
        // 単純に検出された座標をもとに画像データを作成する
        var faceCs = new Canvas(Math.floor(face.width),Math.floor(face.height));
        var faceCtx = faceCs.getContext('2d');
        faceCtx.drawImage(img,Math.floor(face.x),Math.floor(face.y),
                  Math.floor(face.width),Math.floor(face.height),
                  0,0,Math.floor(face.width),Math.floor(face.height));
//      faceCtx.drawImage(img,0,0,256,256,
//                0,0,256,256);
        var out = fs.createWriteStream(__dirname + '/'+gNum+'.png');
        gNum++;
        var stream = faceCs.createPNGStream();
        stream.pipe(out);
        //faceCs.toDataURL(function(err, str) {
    //  var out = fs.createWriteStream(__dirname + '/'+gNum+'.html');
    //  gNum++;
    //  out.write('<img src="' + str + '">');
      //  });
    }
     
    //myDataUrl();
    });
}
 
function myDataUrl() {
    canvas.toDataURL(function(err, str) {
    console.log('<img src="' + str + '">');
    });
}
 
var targetDir = 'camdata';
fs.readdir(targetDir, function (err, files) {
    for(var i = 0; i<files.length;0) {
        console.log(files[i]);
        detectFace(targetDir + "/"+ files[i]);
        if(gFaceDetect) {
        return;
        }
    }
    }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment