node-opencv
OpenCV是一套有名的影像處理工具,透過node.js來搭配OpenCV可以延伸在node.js在影像相關範圍的應用,例如人臉辨識之類的
Installation
npm install node-opencv
在安裝node-opencv之前,需要先完成opencv套件的安裝,可以參考node-opencv來做相關安裝。我在Mac上是這樣裝的:
brew tap homebrew/science
brew install opencv
參考網站:http://www.learnopencv.com/install-opencv-3-on-yosemite-osx-10-10-x/
範例程式
下面是一個簡單的範例程式,可以抓http資源位置或是本地端位置的圖片來做人臉的註記(在人臉不用橢圓形標記起來)
#!/usr/bin/env node
var cv = require('opencv');
var request = require('request');
var fs = require('fs');
var tmpfile = '/tmp/tmpgile';
function detect(imgfile) {
cv.readImage(imgfile, function(err, im){
im.detectObject(cv.FACE_CASCADE, {}, function(err, faces){
for (var i=0;i<faces.length; i++){
var x = faces[i]
console.log('>>', x); //Will see something like: { x: 336, y: 1359, width: 42, height: 42 }
im.ellipse(x.x + x.width/2, x.y + x.height/2, x.width/2, x.height/2);
}
im.save('/tmp/test.jpg');
});
})
}
//Execute the process
if(process.argv[2].indexOf('http') == 0) { //from http resource
var url = process.argv[2];
var req = request.get(url);
req.pipe(fs.createWriteStream(tmpfile));
req.on('end', function(){
detect(tmpfile);
});
} else { //from localhost
detect(process.argv[2]);
}
上面程式存成:face-opencv.js,並給予執行的權限:
$ ./face-opencv.js http://www.pngdot.com/wp-content/uploads/2015/10/People_Png_Transparent_01.png
回覆的結果:
>> { x: 336, y: 1359, width: 42, height: 42 }
>> { x: 322, y: 137, width: 115, height: 115 }
>> { x: 1255, y: 188, width: 109, height: 109 }
>> { x: 1483, y: 93, width: 125, height: 125 }
>> { x: 584, y: 152, width: 111, height: 111 }
>> { x: 933, y: 156, width: 120, height: 120 }
回覆的部分,還會包含/tmp/test.jpg的輸出檔案,而console輸出的訊息代表每個人臉的中心位置以及範圍,透過這些資訊,可以做更多的應用唷!