-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_line_algorithm.py
More file actions
71 lines (57 loc) · 1.91 KB
/
basic_line_algorithm.py
File metadata and controls
71 lines (57 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"""
This program implements a basic line scan-conversion (line drawing)
algorithm. This program uses the Python Imaging Library in order to
assist with line drawing.
"""
# Standard Libraries
import math
# Image module from the Python Imaging Library
from PIL import Image
# Creates an empty black image
image = Image.new(mode = "RGB", size = (500, 500), color = (0,0,0))
def draw_line(x0, y0, x1, y1, color=False):
"""
This function draws a line starting at point (x0, y0) and ending at point
(x1, y1) in a standard coordinate system.
"""
# RGB values
if color:
r, g, b = 255, 255, 255
else:
r, g, b = 255, 0, 0
# If x0 == x1 : the line is vertical
if x0 == x1:
y_min = min(y0, y1)
# Critical loop
for y_coord in range(abs(y1 - y0)):
image.putpixel((x0, y_min + y_coord), (r, g, b))
# Else, the line is not vertical
else:
# Calculates the slope and y-intercept
slope = (y1 - y0) / (x1 - x0)
y_intercept = y1 - (slope * x1)
# Check if |x1 - x0| >= |y1 - y0|
if (abs(x1 - x0) >= abs(y1 - y0)):
x_min = min(x0, x1)
# Critical loop
for x_coord in range(abs(x1 - x0) + 1):
x = x_min + x_coord
y = (slope * x) + y_intercept
y = math.trunc(y)
image.putpixel((x, y), (r, g, b))
# Check if |x1 - x0| < |y1 - y0|
elif (abs(x1 - x0) < abs(y1 - y0)):
y_min = min(y0, y1)
# Critical loop
for y_coord in range(abs(y1 - y0) + 1):
y = y_min + y_coord
x = (y - y_intercept) / slope
x = math.trunc(x)
image.putpixel((x, y), (r, g, b))
def reset_image():
"""
Resets the current image.
"""
for x in range(500):
for y in range(500):
image.putpixel((x, y), (0, 0, 0))