Get points/pixels in a straight line without knowing second coordinate

Tim Stack :

I'm trying to build a function that extends from a specific coordinate at a given angle, and loops through the pixels on that line until it encounters a black pixel.

This is easily implemented if the angle is, for example, 180 degrees. In this case, the search would only extend downwards, adding 1 to the column coordinate in each iteration. However, an angle of e.g. 10 degrees is more complex. I therefore need to presumably mathematically calculate the next pixel at pixel position X.

This answer in a similar question did not help me as the values on the y-axis don't change as expected:

import numpy as np
angle = 90*np.pi/180

x = np.arange(0, 10)
y = np.round(np.sin(angle)*x).astype(int)
print([(x, y) for x, y in zip(x, y)])

prints: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9)]
Which is wrong since I don't expect the y-axis to change, given the 90-degree angle.

The answer to this other question requires a second 'end' coordinate, which I don't have.

Lastly, I found this question, which unfortunately does not have a valid answer. The code in the question seems to return no offsets but floats, whose meaning I am unsure of. When I round the floats, the offsets are wrong:

import numpy

def pol2cart(rotdist, cwangle):
    x = rotdist * numpy.cos(cwangle)
    y = rotdist * numpy.sin(cwangle)
    return round(x), round(y)

print(pol2cart(1, 180))

prints: (-1.0, -1.0) while the expected output is (1.0, 0.0)

The above answer however would also give a consistent offset at each iteration. This would result in only three different angles (horizontal, vertical, and 45 degrees). This is not what's required, as I'd end up with another angle then I put into the function.

EDIT: Example of input

Below image is an example of the image data. The red dot indicates a possible starting position. This dot has a direction, which is not indicated. If the red dot is pointed straight down, then its direction is 180 degrees.

A nested dictionary contains each pixels's coordinates (row, column) and colour values: {1: {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 255, 8: 255,...

enter image description here

Mark Setchell :

I think you can use Bresenham's "Line Algorithm" described here on Wikipedia.

I know you said you only have the start point and no end point, but you know the angle (direction) of travel, and you know that the longest straight line in a rectangle is the diagonal, so if you imagine a line longer than the diagonal, starting at your start point and heading the right direction, you can generate and end point beyond the edges of your rectangle and use that for the other end in the Bresenham algorithm.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=3943&siteId=1