Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29149

Trace boundary using an image pixel array with NodeJS

I have this image which is completely black except for a white object in the middle (it can be anything but it is always completely white). What I would like to do with nodeJs, is trace the boundary of the object (I would like to find all the white points which are next to black) in the image (performance is key!)

With pngjs I can read an image which gives me an array in which each pixels has 4 values (RGBA). Its a one dimensional array. So, suppose the image is 1000 x 1000 pixels it gives me an array of 1000 x 1000 x 4 = 4000000 entries.

The below expression converts x and y into an array index

 var idx = (1000 * y + x) << 2;

 data[idx] = 243;
 data[idx + 1] = 16;
 data[idx + 2] = 16;

Anyway, I could traverse the whole array and register the points where black changes into white, but as I said, performance is very important. I can imagine that some kind of smart iterative search algorithm exists that can follow the boundary somehow :)

Maybe someone knows a library that can help, or an article about how to do this would be great too!!

Upvotes: 0

Views: 717

Answers (1)

Piglet
Piglet

Reputation: 28964

Check out chain codes like Freeman Code. You need 1 contour point to start with. So just iterate through your lines until you hit your object. Then you walk around your object until you reach your starting point. You will get a code that describes the direction you took for every step. This code can be used to calculate various object features or to just draw the contour of your object.

Btw if your obect is always white and your background is always black you don't have to process 4 channels. Red, green or blue channels contain the same information. Just use either one of them.

Upvotes: 1

Related Questions