0

I'm trying to do some image processing with Node.JS. I'm able to extract the information I need, but I'm having a hard time aggregating results from multiple images and writing them to a file.

You'll see 2 lines near the bottom:

console.log(palette);
output.push(palette);

I can print the palette object to the console, but I cannot push it to the output array. I suspect there is some scope issue going on, but I can't seem to figure it out.

Any and all thoughts greatly appreciated.

    fs = require('fs'),
    getPixels = require("get-pixels");

    var startTime = Date.now();
    var imageDirectory = 'input';
    var images = fs.readdirSync(imageDirectory);

    console.log('Found ' + images.length + ' images.');

    var output = [];

    for (var image = 0; image < images.length; image++) {

        getPixels(imageDirectory + '/' + images[image], function(err, pixels) {
            if(err) {
                console.log('Bad image path');
                return
            }

            var palette = {
                coloredPixels: 0,
                hues: [],
                image: images[image],
                classification: false,
                pixelCount: null
            };

            palette.pixelCount = pixels.shape[0] * pixels.shape[1] * pixels.shape[2];

            for(var i=0; i < 256; i++) {
                palette.hues[i] = 0;
            }

            for (var i=0; i < palette.pixelCount; i+=4) {
                var rgb = [pixels.data[i], pixels.data[i+1], pixels.data[i+2]],
                    hsl = convert.rgb.hsl(rgb),
                    hue = hsl[0],
                    saturation = hsl[1];

                if (saturation) {
                    palette.hues[hue]++;
                    palette.coloredPixels++;
                }
            }

            console.log(palette);
            output.push(palette);
        })
    }

    var json = JSON.stringify(output, null, 2); 
    fs.writeFileSync('data.json', json);

    // Calculate time spent
    var endTime = Date.now();
    console.log('Finished in ' + (endTime - startTime) / 1000 + ' seconds.');
Knut
  • 87
  • 1
  • 8

0 Answers0