mercredi 21 décembre 2022

Generate 45 degree (or less) line from 2 randomly generated points

I'm randomly generating 2 points and drawing a line with them. A problem occurs when the line is too steep (> 45 degrees) and the line appears more like spaced out dots than an actual line. Another problem is that if the line is perpendicular (90 degrees, parallel to y axis) the algorithm is dividing my 0 and giving an error out.

So my question is: How can I randomly generate 2 points that make a 45 degree (or less) line?

Point.py:

class Point:
   def __init__(self, x, y):
    self.x = x
    self.y = y

main.py:

from Point import Point
from random import randint

def simple_line(p1, p2):
  # Calculate slope of line
  # y = mx + b
  m = (p2.y - p1.y) / (p2.x - p1.x)

  # Calculate height of line

  b = p1.y - m * p1.x

  return m, b

def draw_lines(img_array, points):
  for p in points:
    m, b = simple_line(p[0], p[1])

    # some code to draw on image.... 


random_points_array = []
 
# Generate lots of lines
for i in range(500):
  random_points_array.append((Point(randint(0, len(img_array[0])), randint(0, len(img_array))), 
                              Point(randint(0, len(img_array[0])), randint(0, len(img_array)))))

draw_lines(random_points_array)



Aucun commentaire:

Enregistrer un commentaire