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

Write a program to clip a line using Cohen and Sutherland line clipping algorithm.ipynb - Colab

as the question says

Uploaded by

sakshikumar.2806
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Write a program to clip a line using Cohen and Sutherland line clipping algorithm.ipynb - Colab

as the question says

Uploaded by

sakshikumar.2806
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

11/5/24, 7:31 PM Write a program to clip a line using Cohen and Sutherland line clipping algorithm.

ipynb - Colab

import matplotlib.pyplot as plt

INSIDE = 0
LEFT = 1
RIGHT = 2
BOTTOM = 4
TOP = 8

x_min, y_min = 50, 50


x_max, y_max = 200, 200

def c_oc(x, y):


code = INSIDE
if x < x_min:
code |= LEFT
elif x > x_max:
code |= RIGHT
if y < y_min:
code |= BOTTOM
elif y > y_max:
code |= TOP
return code

def cohen_sutherland_clip(x1, y1, x2, y2):


oc1 = compute_out_code(x1, y1)
oc2 = c_oc(x2, y2)
accept = False

while True:
if oc1 == 0 and oc2 == 0:
accept = True
break
elif oc1 & oc2 != 0:
break
else:
x, y = 0, 0
oco = oc1 if oc1 != 0 else oc2

if oco & TOP:


x = x1 + (x2 - x1) * (y_max - y1) / (y2 - y1)
y = y_max
elif oco & BOTTOM:
x = x1 + (x2 - x1) * (y_min - y1) / (y2 - y1)
y = y_min
elif oco & RIGHT:
y = y1 + (y2 - y1) * (x_max - x1) / (x2 - x1)
x = x_max
elif oco & LEFT:
y = y1 + (y2 - y1) * (x_min - x1) / (x2 - x1)
x = x_min

if oco == oc1:
x1, y1 = x, y
oc1 = compute_out_code(x1, y1)
else:
x2, y2 = x, y
oc2 = compute_out_code(x2, y2)

if accept:
plt.plot([x1, x2], [y1, y2], 'g')
else:
plt.plot([x1, x2], [y1, y2], 'r')

def drawing_the_clipping_window():
plt.plot([x_min, x_max], [y_min, y_min], 'b')
plt.plot([x_max, x_max], [y_min, y_max], 'b')
plt.plot([x_max, x_min], [y_max, y_max], 'b')
plt.plot([x_min, x_min], [y_max, y_min], 'b')

x1, y1 = 60, 60
x2, y2 = 250, 250

drawing_the_clipping_window()
cohen_sutherland_clip(x1, y1, x2, y2)
plt.xlim(0, 300)
plt.ylim(0, 300)
plt.title('Cohen-Sutherland Line Clipping')
plt.show()

https://colab.research.google.com/drive/1EakMzX6rhS8qPbTDf_JWoln_3DeLGkWC#printMode=true 1/2
11/5/24, 7:31 PM Write a program to clip a line using Cohen and Sutherland line clipping algorithm.ipynb - Colab

https://colab.research.google.com/drive/1EakMzX6rhS8qPbTDf_JWoln_3DeLGkWC#printMode=true 2/2

You might also like