Skip to content

Instantly share code, notes, and snippets.

@p0wdrdotcom
Created March 6, 2017 22:24
Show Gist options
  • Save p0wdrdotcom/d6a145771a391405f445ae91a0c3ae5e to your computer and use it in GitHub Desktop.
Save p0wdrdotcom/d6a145771a391405f445ae91a0c3ae5e to your computer and use it in GitHub Desktop.
A converter from new opencv XML format for JSFeat for use with jsfeat.haar.detect_multi_scale
var XmlStream = require('xml-stream');
/**
* Constructor
*/
function ConverterJSFeat() {
if (!(this instanceof ConverterJSFeat))
return new ConverterJSFeat();
}
/**
* Converts the new type of opencv haarcascade
* classifiers to an internal representation.
* @param {stream} stream stream of xml
* @param {Function} cb callback function
* to be resolved with
* (err|data), w/ data
* being the result
* structure
*/
ConverterJSFeat.prototype.convert = function(stream, cb) {
if (!stream)
throw new Error('A stream must be passed');
var xml = new XmlStream(stream);
var haarStruct = {
complexClassifiers: [],
features: [],
size: [0, 0],
tilted: false
};
xml.collect('_');
xml.on('endElement: cascade > height', function(item) {
var h = +item['$text'];
haarStruct.size[1] = h;
});
xml.on('endElement: cascade > width', function(item) {
var w = +item['$text'];
haarStruct.size[0] = w;
});
xml.on('endElement: stages > _', function(item) {
let stage = {
threshold: parseFloat(item.stageThreshold),
simpleClassifiers: []
};
var maxWeakCount = +item.maxWeakCount;
for (var i = 0; i < maxWeakCount; i++) {
var internalNodes = item
.weakClassifiers['_'][i]
.internalNodes.split(' ');
var leafValues = item
.weakClassifiers['_'][i]
.leafValues.split(' ');
var node = {
left_val: '',
right_val: '',
threshold: '',
features: []
};
node.left_val = parseFloat(leafValues[0]);
node.right_val = parseFloat(leafValues[1]);
node.f = +internalNodes[2];
node.threshold = parseFloat(internalNodes[3]);
stage.simpleClassifiers.push(node);
}
haarStruct.complexClassifiers.push(stage);
});
xml.on('endElement: features > _', function(item) {
haarStruct.features.push({
rects: item.rects['_'],
tilted: +item.tilted ? 1 : 0
});
});
xml.on('error', function(err) {
cb(err);
});
xml.on('end', function() {
var features = haarStruct.features;
var f = features.length;
var g = 0;
haarStruct.complexClassifiers.forEach(function (stage) {
stage.simpleClassifiers.forEach(function (weakClassifier) {
g++;
var rects = features[weakClassifier.f].rects.map(function (rect) {
return rect.split(' ').map(function (numberString) {
return +numberString;
});
});
delete weakClassifier.f;
weakClassifier.features = rects;
});
});
console.log(f, g);
delete haarStruct.features;
return cb(null, haarStruct);
});
};
module.exports = ConverterJSFeat;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment