Tom
Tom

Reputation: 1565

Converting an image to rows of grayscale pixel values

I'd like to use the node indico API. I need to convert the image to grayscale and then to arrays containing arrays/rows of pixel values. Where do I start?

These tools take a specific format for images, a list of lists, each sub-list containing a 'row' of values corresponding to n pixels in the image.

e.g. [[float, float, float ... *n ], [float, float, float ... *n ], ... *n]

Since pixels tend to be represented by RGBA values, you can use the following formula to convert to grayscale.

Y = (0.2126 * R + 0.7152 * G + 0.0722 * B) * A

We're working on automatically scaling images, but for the moment it's up to you provide a square image

Upvotes: 5

Views: 3556

Answers (2)

Lovell Fuller
Lovell Fuller

Reputation: 717

I maintain the sharp Node.js module that may be able to get you a little closer to what you need.

The following example will convert input to greyscale and generate a Bufferof integer values, one byte per pixel.

You'll need to add logic to divide by 255 to convert to float then split into an array of arrays to keep the Indico API happy.

sharp(input)
  .resize(width, height)
  .grayscale()
  .raw()
  .toBuffer(function(err, data) {
    // data is a Buffer containing uint8 values (0-255)
    // with each byte representing one pixel
  });

Upvotes: 4

Slater Victoroff
Slater Victoroff

Reputation: 21914

It looks like node's image manipulation tools are sadly a little lacking, but there is a good solution.

get-pixels allows reading in images either from URL or from local path and will convert it into an ndarray that should work excellently for the API.

The API will accept RGB images in the format that get-pixels produces them, but if you're still interested in converting the images to grayscale, which can be helpful for other applications it's actually a little strange.

In a standard RGB image there's basically a luminence score given to each color, which is how bright the color appears. Based on the luminance, a conversion to grayscale for each pixel happens as follows:

Grayscale = 0.2126*R + 0.7152*G + 0.0722*B

Soon the API will also support the direct use of URLs, stay tuned on that front.

Upvotes: 4

Related Questions