2014-09-18 36 views
0

我試圖加載了很多這是在CVS文件中所列的以下格式加載圖像與OpenCV的圖像列表:在Node.js的

./path/to/img1.ext;label1 
./path/to/img2.ext;label2 

這是我的腳本寫:

var cv = require("opencv"), 
    fs = require("fs"), 
    console = require("console"), 
    util = require("util"), 
    lazy = require("lazy.js"); 

var basePath = '/some/path/'; 

var csvFile = fs.createReadStream(basePath + 'db.csv', {flags:'r'}); 

var images = [], 
    labels = []; 

lazy(csvFile) 
.lines() 
.each(function(l) { 
    var d = lazy(l).split(';').toArray(); 
    cv.readImage(basePath + d[0], function(e, m) { 
     images.push(m); 
    }); 
    labels.push(d[1]); 
}); 

console.log(util.inspect(images)); 
console.log(util.inspect(labels)); 

它打印含有一個空數組[]的表示兩個線路。

的圖像實際上是過得去OpenCV的加載,因爲如果你試圖將其推入陣列之前打印m它正確打印[Matrix HxW ],其中HW代表的高度和圖像的寬度。

編輯:另外,你可以想到一個更好的方式比2分離數組保持每個圖像與其標籤相關聯?

編輯:問題似乎是圖像加載異步。所以問題在於我缺乏異步編程的經驗。我該如何做這項工作?

+0

你嘗試過這個庫的節點? https://github.com/caolan/async – gabereal 2014-09-18 19:04:22

+0

@gabereal:應該怎樣幫助我? – 2014-09-18 19:09:25

+0

你可以延遲每個循環的迭代,直到readImage(我從你的第二次編輯中假定是異步部分)回調完成執行。有什麼好的理由使用懶惰?我不明白你爲什麼不使用'fs'和'readline'節點模塊... – gabereal 2014-09-18 20:09:37

回答

0

這裏是使用管道和CSV2和through2庫節點,你可以在這裏找到https://github.com/rvagg/csv2的解決方案,並在這裏https://github.com/rvagg/through2

我使用的setTimeout模擬異步函數測試這和它的工作。然而,因爲我沒有你的數據文件,我無法準確測試它。請讓我知道是否有問題。

注意我創建了一個對象數組。每個物體都有圖像和標籤。我認爲這是比試圖用這些關聯保持兩個數組更好的解決方案。一般來說,如果你需要與你的數據關係,對象將好於兩個數組:)

var fs = require('fs'); 
var files = []; 
var file = fs.createReadStream('test.txt'); 
var csv2 = require('csv2'); 
var th2 = require('through2'); 
var cv = require('opencv'); 

file 
.pipe(csv2({'separator': ';'})).pipe(th2({objectMode: true},function(parsedLine, enc, callback){ 
    var me = this; 
    cv.readImage(parsedLine[0], function(e, img) { 
     files.push({image: img, label: parsedLine[1]}); 
     me.push(parsedLine); 
     callback(); 
    }); 
})) 
.on('data', function(data){/*do something with data if you want to*/}) 
.on('end', function(){console.log(files);});