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

Cg Practical File

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)
9 views

Cg Practical File

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/ 21

1|Pa ge

RAM LAL ANAND COLLEGE

PRACTICAL
FILE
NAME: SAKSHI KUMAR

ROLL NUMBER: 4051

COURSE: BSc Hons Computer

Science

SUBJECT: COMPUTER GRAPHICS

SUBMITTED TO: Mr. Hemant


2|Pa ge

INDEX
CONTENT PAGE NUMEBRS
1. Write a program to implement Bresenham’s line drawing algorithm. 3
2. Write a program to implement a midpoint circle drawing algorithm. 5
3. Write a program to clip a line using Cohen and Sutherland line 7
clipping algorithm.
4. Write a program to clip a polygon using Sutherland Hodgemann 10
algorithm.
5. Write a program to fill a polygon using the Scan line fill algorithm. 13
6. Write a program to apply various 2D transformations on a 2D object 15
(use homogeneous Coordinates).
7. Write a program to apply various 3D transformations on a 3D object 17
and then apply parallel and perspective projection on it.
8. Write a program to draw Hermite /Bezier curve. 20
3|Pa ge

1. Write a program to implement Bresenham’s line drawing algorithm.


INPUT
import matplotlib.pyplot as plt
a0=int(input("ENTER X0: "))
b0=int(input("ENTER Y0: "))
a1=int(input("ENTER X1: "))
b1=int(input("ENTER Y1: "))
def mid_point_line(x0, y0, x1, y1):
dy=y1-y0
dx=x1-x0
d=2*dy-dx
incrE=2*dy
incrNE=2*(dy-dx)
x=x0
y=y0
points = [(x, y)]

while(x<x1):
if(d<=0):
d+=incrE
x+=1
else:
d+=incrNE
x+=1
y+=1
points.append((x, y))
return points
line_points = mid_point_line(a0, b0, a1, b1)
plt.plot(*zip(*line_points), marker='o', color='b')
plt.grid(True)
plt.show()
4|Pa ge

OUTPUT
5|Pa ge

2. Write a program to implement a midpoint circle drawing algorithm.


INPUT
import matplotlib.pyplot as plt
def circle_points(x,y):
plt.plot(x, y, marker='o',color='b')
plt.plot(y, x, marker='o',color='b')
plt.plot(y, -x, marker='o',color='b')
plt.plot(x, -y, marker='o',color='b')
plt.plot(-x, -y, marker='o',color='b')
plt.plot(-y, -x, marker='o',color='b')
plt.plot(-y, x, marker='o',color='b')
plt.plot(-x, y, marker='o',color='b')
plt.plot(-x, y, marker='o',color='b')

def Midpoint_circle(radius):
x=0
y=radius
d=5.0/4.0-radius
circle_points(x,y)
while(y>x):
if(d<0):
d+=2.0*x+3.0
else:
d+=2.0*(x-y)+5.0
y-=1
x+=1
circle_points(x,y)

Midpoint_circle(20)
plt.grid(True)
plt.show()
6|Pa ge

OUTPUT
7|Pa ge

3. Write a program to clip a line using Cohen and Sutherland line clipping
algorithm.
INPUT
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)
8|Pa ge

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()
9|Pa ge

OUTPUT
10 | P a g e

4. Write a program to clip a polygon using Sutherland Hodgemann


algorithm.
INPUT
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)


11 | P a g e

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

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

plt.show()

OUTPUT
12 | P a g e
13 | P a g e

5. Write a program to fill a polygon using the Scan line fill algorithm.
INPUT
import matplotlib.pyplot as plt
import numpy as np

def edge_table(vertices):
edges = []
for i in range(len(vertices)):
x1, y1 = vertices[i]
x2, y2 = vertices[(i + 1) % len(vertices)]
if y1 != y2:
if y1 > y2:
x1, y1, x2, y2 = x2, y2, x1, y1
edges.append((x1, y1, x2, y2))
return edges

def scanline_fill(vertices):
edges = edge_table(vertices)
y_min = min([y for _, y, _, _ in edges])
y_max = max([y for _, y, _, _ in edges])

for y in range(y_min, y_max + 1):


intersections = []
for x1, y1, x2, y2 in edges:
if y1 <= y < y2 or y2 <= y < y1:
x = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
intersections.append(x)
intersections.sort()

for i in range(0, len(intersections), 2):


x_start = int(intersections[i])
x_end = int(intersections[i + 1])
plt.plot(range(x_start, x_end + 1), [y] * (x_end - x_start + 1), color='black')

def draw_polygon(vertices):
vertices = np.array(vertices)
plt.fill(vertices[:, 0], vertices[:, 1], edgecolor='black', fill=False)
scanline_fill(vertices)
plt.show()

vertices = [(10, 10), (100, 50), (90, 100), (50, 70), (20, 90)]
draw_polygon(vertices)
14 | P a g e

OUTPUT
15 | P a g e

6. Write a program to apply various 2D transformations on a 2D object (use


homogeneous Coordinates).
INPUT
import numpy as np

# Define a 2D object as a set of points


points = np.array([
[1, 1, 1],
[2, 1, 1],
[2, 2, 1],
[1, 2, 1]
])

# Translation matrix
def translation(tx, ty):
return np.array([
[1, 0, tx],
[0, 1, ty],
[0, 0, 1]
])

# Scaling matrix
def scaling(sx, sy):
return np.array([
[sx, 0, 0],
[ 0, sy, 0],
[ 0, 0, 1]
])

# Rotation matrix
def rotation(angle):
rad = np.deg2rad(angle)
return np.array([
[ np.cos(rad), -np.sin(rad), 0],
[ np.sin(rad), np.cos(rad), 0],
[ 0, 0, 1]
])

# Apply transformation
def apply_transformation(points, transformation_matrix):
return np.dot(points, transformation_matrix.T)

# Example of transformations
translated_points = apply_transformation(points, translation(1, 2))
scaled_points = apply_transformation(points, scaling(2, 2))
rotated_points = apply_transformation(points, rotation(45))
16 | P a g e

print("Original Points:\n", points)


print("Translated Points:\n", translated_points)
print("Scaled Points:\n", scaled_points)
print("Rotated Points:\n", rotated_points)

OUTPUT
17 | P a g e

7. Write a program to apply various 3D transformations on a 3D object and


then apply parallel and perspective projection on it.
INPUT
import numpy as np

points = np.array([
[1, 1, 1, 1],
[2, 1, 1, 1],
[2, 2, 1, 1],
[1, 2, 1, 1],
[1, 1, 2, 1],
[2, 1, 2, 1],
[2, 2, 2, 1],
[1, 2, 2, 1]
])

def translation(tx, ty, tz):


return np.array([
[1, 0, 0, tx],
[0, 1, 0, ty],
[0, 0, 1, tz],
[0, 0, 0, 1]
])

def scaling(sx, sy, sz):


return np.array([
[sx, 0, 0, 0],
[ 0, sy, 0, 0],
[ 0, 0, sz, 0],
[ 0, 0, 0, 1]
])

def rotation_x(angle):
rad = np.deg2rad(angle)
return np.array([
[1, 0, 0, 0],
[0, np.cos(rad), -np.sin(rad), 0],
[0, np.sin(rad), np.cos(rad), 0],
[0, 0, 0, 1]
])

def rotation_y(angle):
rad = np.deg2rad(angle)
return np.array([
[np.cos(rad), 0, np.sin(rad), 0],
[0, 1, 0, 0],
18 | P a g e

[-np.sin(rad), 0, np.cos(rad), 0],


[0, 0, 0, 1]
])

def rotation_z(angle):
rad = np.deg2rad(angle)
return np.array([
[np.cos(rad), -np.sin(rad), 0, 0],
[np.sin(rad), np.cos(rad), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
])

def atrans(points, transformation_matrix):


return np.dot(points, transformation_matrix.T)

def parallel_projection():
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 1]
])

def perspective_projection(d):
return np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 1/d, 0]
])

translated_points = atrans(points, translation(1, 2, 3))


scaled_points = atrans(points, scaling(2, 2, 2))
rotated_points_x = atrans(points, rotation_x(45))
rotated_points_y = atrans(points, rotation_y(45))
rotated_points_z = atrans(points, rotation_z(45))

parallel_projected_points = atrans(points, parallel_projection())


perspective_projected_points = atrans(points, perspective_projection(2))

print("Original Points:\n", points)


print("Translated Points:\n", translated_points)
print("Scaled Points:\n", scaled_points)
print("Rotated Points (X-axis):\n", rotated_points_x)
print("Rotated Points (Y-axis):\n", rotated_points_y)
print("Rotated Points (Z-axis):\n", rotated_points_z)
print("Parallel Projected Points:\n", parallel_projected_points)
19 | P a g e

print("Perspective Projected Points:\n", perspective_projected_points)

OUTPUT
20 | P a g e

8. Write a program to draw Hermite /Bezier curve.


INPUT
import numpy as np
import matplotlib.pyplot as plt

def bezier_curve(points, n_points=100):


t = np.linspace(0, 1, n_points)
curve = np.zeros((n_points, 2))

for i in range(len(points)):
curve += np.outer((1 - t)**(len(points) - 1 - i) * t**i, points[i]) * comb(len(points) - 1, i)

return curve

def comb(n, k):


"""Calculate the binomial coefficient."""
if k == 0 or k == n:
return 1
return comb(n - 1, k - 1) + comb(n - 1, k)

# Define control points


control_points = np.array([
[0, 0],
[1, 2],
[3, 3],
[4, 0]
])

# Get the Bezier curve points


curve = bezier_curve(control_points)

# Plot the Bezier curve


plt.plot(curve[:, 0], curve[:, 1], label="Bezier Curve")
plt.plot(control_points[:, 0], control_points[:, 1], 'ro-', label="Control Points")
plt.legend()
plt.title("Bezier Curve")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()
21 | P a g e

OUTPUT

You might also like