0% found this document useful (0 votes)
11 views

Write a program to clip a polygon using Sutherland Hodgeman algorithm.ipynb - Colab

as the question says

Uploaded by

sakshikumar.2806
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Write a program to clip a polygon using Sutherland Hodgeman algorithm.ipynb - Colab

as the question says

Uploaded by

sakshikumar.2806
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

11/5/24, 7:24 PM Write a program to clip a polygon using Sutherland Hodgeman algorithm.

ipynb - Colab

import matplotlib.pyplot as plt

def inside(p, edge):


(x, y), (x1, y1), (x2, y2) = p, edge[0], edge[1]
return (x2 - x1) * (y - y1) >= (y2 - y1) * (x - x1)

def intersection(p1, p2, edge):


(x1, y1), (x2, y2) = p1, p2
(x3, y3), (x4, y4) = edge[0], edge[1]
a1, b1, a2, b2 = y2 - y1, x1 - x2, y4 - y3, x3 - x4
c1, c2 = a1 * x1 + b1 * y1, a2 * x3 + b2 * y3
det = a1 * b2 - a2 * b1
if det != 0:
x = (b2 * c1 - b1 * c2) / det
y = (a1 * c2 - a2 * c1) / det
return (x, y)
return None

def clip_polygon(polygon, edges):


for edge in edges:
new_polygon = []
for i in range(len(polygon)):
p1 = polygon[i]
p2 = polygon[(i + 1) % len(polygon)]
if inside(p2, edge):
if not inside(p1, edge):
new_polygon.append(intersection(p1, p2, edge))
new_polygon.append(p2)
elif inside(p1, edge):
new_polygon.append(intersection(p1, p2, edge))
polygon = new_polygon
return polygon

def draw_polygon(polygon):
polygon.append(polygon[0])
xs, ys = zip(*polygon)
plt.plot(xs, ys)

# Example
polygon = [(10, 10), (100, 30), (90, 90), (20, 70)]
clip_edges = [[(20, 20), (80, 20)], [(80, 20), (80, 80)], [(80, 80), (20, 80)], [(20, 80), (20, 20)]]

clipped_polygon = clip_polygon(polygon, clip_edges)

plt.figure()
draw_polygon(polygon)
plt.title("Original Polygon")

plt.figure()
draw_polygon(clipped_polygon)
plt.title("Clipped Polygon")

plt.show()

https://colab.research.google.com/drive/1JZ4Fk7dl1IwnDqMqf2V_j2x9s8ly95vU#scrollTo=NwlVOhPlmILQ&printMode=true 1/2
11/5/24, 7:24 PM Write a program to clip a polygon using Sutherland Hodgeman algorithm.ipynb - Colab

https://colab.research.google.com/drive/1JZ4Fk7dl1IwnDqMqf2V_j2x9s8ly95vU#scrollTo=NwlVOhPlmILQ&printMode=true 2/2

You might also like