Search code examples
processing

Store pixels from image along a line of points into an array


I have an image and I'm trying to store the pixel colors for a set of points along a line into an array.

The endpoints of the line and the distance between points is given. I know that the command line(x1,y1,x2,y2) draws a line between (x1,y1) and (x2,y2). I also know that .get() applied to an image returns the pixel color at the specified location.

I am unsure how to put it all together.


Solution

  • Essentially the problem is in two parts:

    1. working out which pixel of the image you are over at each point along the line
    2. Reading out that pixel value and storing it in an array

    The second is fairly simple: https://processing.org/reference/PImage_get_.html will give you all the info you need about getting the pixel values at a certain coordinate.

    The first is a maths problem essentially.

    The line you draw will have the equation: Y = m * X + C where C is the intercept of the X axis and M is its gradient.

    (One thing to remember is that the origin (0,0) for a processing sketch is at the top left)

    https://www.mathsisfun.com/algebra/line-equation-2points.html is a good resource for this. The basic methodology is to calculate the gradient M and then set Y to 0 and equate m * X = -C