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

Practical Computer Graphics

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

Practical Computer Graphics

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

Ram Krishna Dharmarth Foundation

University, Bhopal , M.P.

Semester-5
Practical on :
Computer Graphics
BCA-501/M1T
Submitted By

Student Name :- - - - - - - - - - - - - -

Enrollment No. :- - - - - - - - - - - - - -

Dr.N.K.Shrivastava Mr. Anand Kumar


Head Assistant Professor

Faculty of Computer Application


Session-2024-25
1. Write a Program to draw basic graphics construction like line, circle, arc, ellipse and rectangle.
Here’s a Python program that uses the turtle module to draw basic graphics such as lines, circles, arcs,
ellipses, and rectangles. The turtle module is part of Python's standard library and is excellent for drawing
simple graphics.
python
Copy code
import turtle
import math

# Setup the turtle screen


screen = turtle.Screen()
screen.title("Basic Graphics Drawing")

# Create a turtle object


pen = turtle.Turtle()
pen.speed(3)

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


"""Draws a line from (x1, y1) to (x2, y2)."""
pen.penup()
pen.goto(x1, y1)
pen.pendown()
pen.goto(x2, y2)

def draw_circle(x, y, radius):


"""Draws a circle with center (x, y) and radius."""
pen.penup()
pen.goto(x, y - radius)
pen.pendown()
pen.circle(radius)

def draw_arc(x, y, radius, start_angle, extent):


"""Draws an arc with given radius and angles."""
pen.penup()
pen.goto(x, y - radius)
pen.setheading(start_angle)
pen.pendown()
pen.circle(radius, extent)

def draw_ellipse(x, y, a, b):


"""Draws an ellipse centered at (x, y) with radii a and b."""
pen.penup()
pen.goto(x + a, y)
pen.pendown()
pen.setheading(0)
for angle in range(0, 360, 2): # Increment angle to approximate the ellipse

radian = math.radians(angle)
x_offset = a * math.cos(radian)
y_offset = b * math.sin(radian)
pen.goto(x + x_offset, y + y_offset)

def draw_rectangle(x, y, width, height):


"""Draws a rectangle starting from (x, y) with given width and height."""
pen.penup()
pen.goto(x, y)
pen.pendown()
for _ in range(2):
pen.forward(width)
pen.left(90)
pen.forward(height)
pen.left(90)

# Drawing shapes
draw_line(-100, 0, 100, 0) # Line
draw_circle(0, 0, 50) # Circle
draw_arc(200, 0, 50, 0, 180) # Arc
draw_ellipse(-200, 0, 80, 40) # Ellipse
draw_rectangle(-50, -150, 100, 50) # Rectangle

# Finish
pen.hideturtle()
screen.mainloop()
Explanation:
1. Line: Uses two points to draw a straight line.
2. Circle: Drawn using the circle method of the turtle module.
3. Arc: Partial circle using the circle method with an extent angle.
4. Ellipse: Approximates the ellipse using parametric equations and a loop.
5. Rectangle: Drawn with four sides using the forward and left methods.

Run the program in a Python environment to see the graphics drawn on the screen.

2. Write a program of Translation, Rotation, and Scaling using Composite Transformation.


Below is a Python program that implements Translation, Rotation, and Scaling using Composite
Transformation. It uses basic linear algebra concepts and the matplotlib library for visualization.

Python Program: Composite Transformation


python
Copy code
import numpy as np
import matplotlib.pyplot as plt

def plot_shape(points, title, color='blue'):


"""Plot the given shape points."""
points = np.vstack((points, points[0])) # Close the shape
plt.plot(points[:, 0], points[:, 1], color=color, marker='o')
plt.title(title)
plt.grid(True)
plt.axis('equal')
def translate(points, tx, ty):
"""Apply translation transformation."""
translation_matrix = np.array([
[1, 0, tx],
[0, 1, ty],
[0, 0, 1]
])
points_homogeneous = np.hstack((points, np.ones((points.shape[0], 1))))
transformed_points = points_homogeneous @ translation_matrix.T
return transformed_points[:, :2]

def rotate(points, angle):


"""Apply rotation transformation."""

rad = np.radians(angle)
rotation_matrix = np.array([
[np.cos(rad), -np.sin(rad), 0],
[np.sin(rad), np.cos(rad), 0],
[0, 0, 1]
])
points_homogeneous = np.hstack((points, np.ones((points.shape[0], 1))))
transformed_points = points_homogeneous @ rotation_matrix.T
return transformed_points[:, :2]

def scale(points, sx, sy):


"""Apply scaling transformation."""
scaling_matrix = np.array([
[sx, 0, 0],
[0, sy, 0],
[0, 0, 1]
])
points_homogeneous = np.hstack((points, np.ones((points.shape[0], 1))))
transformed_points = points_homogeneous @ scaling_matrix.T
return transformed_points[:, :2]

def composite_transform(points, tx, ty, angle, sx, sy):


"""Apply composite transformation: Translation -> Rotation -> Scaling."""
points_translated = translate(points, tx, ty)
points_rotated = rotate(points_translated, angle)
points_scaled = scale(points_rotated, sx, sy)
return points_scaled

# Define the original shape (triangle in this case)


original_points = np.array([
[0, 0],
[1, 0],

[0.5, 1]
])

# Parameters for transformations


tx, ty = 2, 3 # Translation
angle = 45 # Rotation in degrees
sx, sy = 1.5, 2 # Scaling factors

# Perform transformations
transformed_points = composite_transform(original_points, tx, ty, angle, sx, sy)

# Plot original and transformed shapes


plt.figure(figsize=(8, 8))
plot_shape(original_points, "Original Shape", color='blue')
plot_shape(transformed_points, "Transformed Shape", color='red')
plt.legend(["Original", "Transformed"])
plt.show()

Explanation:
1. Translation:
o Moves the shape by (tx, ty) using a translation matrix: T=[10tx01ty001]T = \begin{bmatrix} 1
& 0 & tx \\ 0 & 1 & ty \\ 0 & 0 & 1 \end{bmatrix}T=100010txty1
2. Rotation:
o Rotates the shape by an angle (in degrees) using a rotation matrix:
R=[cos⁡(θ)−sin⁡(θ)0sin⁡(θ)cos⁡(θ)0001]R = \begin{bmatrix} \cos(\theta) & -\sin(\theta) &
0 \\ \sin(\theta) & \cos(\theta) & 0 \\ 0 & 0 & 1 \end{bmatrix}R=cos(θ)sin(θ)0−sin(θ)cos(θ)0
001
3. Scaling:
o Scales the shape by factors (sx, sy) using a scaling matrix: S=[sx000sy0001]S =
\begin{bmatrix} sx & 0 & 0 \\ 0 & sy & 0 \\ 0 & 0 & 1 \end{bmatrix}S=sx000sy0001
4. Composite Transformation:
o Combines Translation → Rotation → Scaling in sequence.

Output:
• A matplotlib plot displaying:
o The original shape (blue).
o The transformed shape (red).
You can modify the shape and transformation parameters (tx, ty, angle, sx, sy) to see different results.
3. Write a program to draw a Circle using midpoint implementation Method.
Here is a Python program to draw a circle using the Midpoint Circle Algorithm. This algorithm efficiently
calculates the points of a circle in a rasterized grid, making it ideal for graphical implementations.

Python Program: Midpoint Circle Algorithm


python
Copy code
import matplotlib.pyplot as plt

def plot_circle_points(x_center, y_center, x, y):


"""Plot the eight symmetric points of the circle."""
points = [
(x_center + x, y_center + y),
(x_center - x, y_center + y),
(x_center + x, y_center - y),
(x_center - x, y_center - y),
(x_center + y, y_center + x),
(x_center - y, y_center + x),
(x_center + y, y_center - x),
(x_center - y, y_center - x)
]
for px, py in points:
plt.plot(px, py, 'bo')

def draw_circle_midpoint(x_center, y_center, radius):


"""Draw a circle using the midpoint circle algorithm."""
x=0
y = radius

d = 1 - radius # Initial decision parameter

plot_circle_points(x_center, y_center, x, y)

while x < y:
x += 1
if d < 0:
d += 2 * x + 1
else:
y -= 1
d += 2 * (x - y) + 1
plot_circle_points(x_center, y_center, x, y)

# Parameters for the circle


x_center = 0 # X-coordinate of the center
y_center = 0 # Y-coordinate of the center
radius = 20 # Radius of the circle

# Draw the circle


plt.figure(figsize=(6, 6))
draw_circle_midpoint(x_center, y_center, radius)

# Set up plot aesthetics


plt.title("Circle using Midpoint Algorithm")
plt.xlabel("X")
plt.ylabel("Y")
plt.grid(True)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()

Explanation:
1. Midpoint Circle Algorithm:

o The circle is drawn using its symmetry; only one-eighth of the circle is computed, and other
points are mirrored.
o The decision parameter ddd determines whether the next pixel will be directly horizontal or
diagonal.
2. Plot Points:
o Eight points symmetric around the circle's center are calculated and plotted for each step.
3. Decision Parameter Update:
o Initial d=1−rd = 1 - rd=1−r.
o If d<0d < 0d<0, the next pixel is directly horizontal (d=d+2x+1d = d + 2x + 1d=d+2x+1).
o Otherwise, the next pixel is diagonal (d=d+2(x−y)+1d = d + 2(x - y) + 1d=d+2(x−y)+1).

Output:
• The program uses Matplotlib to display a rasterized circle on a grid.
• You can adjust the x_center, y_center, and radius variables to modify the circle's properties.

4. Write a program to draw Bezier curve.


Here’s a Python program to draw a Bezier Curve using the De Casteljau's algorithm. This approach is
commonly used to calculate points on a Bezier curve for given control points.

Python Program: Bezier Curve


python
Copy code
import numpy as np
import matplotlib.pyplot as plt

def bezier_curve(control_points, n_points=100):


"""
Calculate points on a Bezier curve using De Casteljau's algorithm.

Parameters:
control_points (list of tuples): Control points [(x1, y1), (x2, y2), ...].
n_points (int): Number of points on the curve to compute.

Returns:
np.array: Points on the Bezier curve.
"""
def de_casteljau(points, t):
"""Recursive implementation of De Casteljau's algorithm."""
if len(points) == 1:
return points[0]
new_points = [
(1 - t) * np.array(points[i]) + t * np.array(points[i + 1])
for i in range(len(points) - 1)
]
return de_casteljau(new_points, t)

curve = [de_casteljau(control_points, t) for t in np.linspace(0, 1, n_points)]


return np.array(curve)

# Define control points for the Bezier curve


control_points = [(0, 0), (2, 4), (4, 2), (6, 0)]
# Calculate Bezier curve points
curve_points = bezier_curve(control_points)

# Plot the Bezier curve and control points


plt.figure(figsize=(8, 6))
control_points_np = np.array(control_points)

# Draw control polygon


plt.plot(control_points_np[:, 0], control_points_np[:, 1], 'k--', label="Control Polygon")

# Draw control points


plt.plot(control_points_np[:, 0], control_points_np[:, 1], 'ro', label="Control Points")

# Draw Bezier curve


plt.plot(curve_points[:, 0], curve_points[:, 1], 'b-', label="Bezier Curve")

# Configure the plot


plt.title("Bezier Curve")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.show()

Explanation:
1. Control Points:
o The Bezier curve is defined by a series of control points (x1,y1),(x2,y2),…,(xn,yn)(x_1, y_1),
(x_2, y_2), \ldots, (x_n, y_n)(x1,y1),(x2,y2),…,(xn,yn).
o In the example, [(0,0),(2,4),(4,2),(6,0)][(0, 0), (2, 4), (4, 2), (6, 0)][(0,0),(2,4),(4,2),(6,0)] are
used.
2. De Casteljau's Algorithm:
o Recursively computes intermediate points based on the parameter t∈[0,1]t \in [0, 1]t∈[0,1].
o The recursion stops when only one point remains, which lies on the curve.
3. Bezier Curve Points:
o The algorithm computes nnn points along the curve, where nnn is defined by n_points.
4. Plot:
o The control polygon (dashed lines connecting control points) is drawn for reference.
o The Bezier curve is drawn as a smooth blue curve.

Output:
• A smooth Bezier curve is plotted along with its control polygon and control points.
• You can modify the control points in the control_points list to change the shape of the curve.

5. Write a Program to rotate a rectangle about its midpoint.


Here is a Python program to rotate a rectangle about its midpoint. The program calculates the new vertices
of the rotated rectangle using rotation matrices and then plots the original and rotated rectangles using
matplotlib.

Python Program: Rotate Rectangle About Its Midpoint


python
Copy code
import numpy as np
import matplotlib.pyplot as plt

def rotate_point(point, center, angle):


"""
Rotate a point around a center by a given angle.

Parameters:
point (tuple): The point (x, y) to rotate.
center (tuple): The center of rotation (cx, cy).
angle (float): The angle in degrees to rotate.

Returns:
tuple: The rotated point (x', y').
"""
rad = np.radians(angle) # Convert angle to radians
cos_theta, sin_theta = np.cos(rad), np.sin(rad)

# Translate point to origin


x, y = point[0] - center[0], point[1] - center[1]

# Apply rotation matrix


x_rotated = x * cos_theta - y * sin_theta
y_rotated = x * sin_theta + y * cos_theta

# Translate back to the center


return x_rotated + center[0], y_rotated + center[1]

def rotate_rectangle(vertices, angle):


"""
Rotate a rectangle around its midpoint.

Parameters:
vertices (list of tuples): List of four vertices [(x1, y1), (x2, y2), ...].
angle (float): The angle in degrees to rotate.

Returns:
list of tuples: The rotated vertices.
"""
# Calculate the midpoint of the rectangle
center = np.mean(vertices, axis=0)

# Rotate each vertex around the center


rotated_vertices = [rotate_point(vertex, center, angle) for vertex in vertices]
return rotated_vertices
# Define the original rectangle vertices
rectangle_vertices = [(2, 1), (6, 1), (6, 3), (2, 3)] # Example rectangle

# Rotation angle in degrees


angle = 45

# Rotate the rectangle


rotated_vertices = rotate_rectangle(rectangle_vertices, angle)

# Plot the original and rotated rectangles


plt.figure(figsize=(8, 6))

# Original rectangle

rectangle_vertices_np = np.array(rectangle_vertices + [rectangle_vertices[0]]) # Close the rectangle


plt.plot(rectangle_vertices_np[:, 0], rectangle_vertices_np[:, 1], 'b-', label="Original Rectangle")

# Rotated rectangle
rotated_vertices_np = np.array(rotated_vertices + [rotated_vertices[0]]) # Close the rectangle
plt.plot(rotated_vertices_np[:, 0], rotated_vertices_np[:, 1], 'r--', label="Rotated Rectangle")

# Midpoint
center = np.mean(rectangle_vertices, axis=0)
plt.plot(center[0], center[1], 'go', label="Midpoint")

# Configure plot
plt.title(f"Rectangle Rotation (Angle = {angle}°)")
plt.xlabel("X")
plt.ylabel("Y")
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.show()
Explanation:
1. Rotation Matrix:
o The rotation formula for a point (x,y)(x, y)(x,y) about a center (cx,cy)(cx, cy)(cx,cy) is:
x′=(x−cx)⋅cos⁡(θ)−(y−cy)⋅sin⁡(θ)+cxx' = (x - cx) \cdot \cos(\theta) - (y - cy) \cdot \sin(\theta)
+ cxx′=(x−cx)⋅cos(θ)−(y−cy)⋅sin(θ)+cx y′=(x−cx)⋅sin⁡(θ)+(y−cy)⋅cos⁡(θ)+cyy' = (x - cx) \cdot
\sin(\theta) + (y - cy) \cdot \cos(\theta) + cyy′=(x−cx)⋅sin(θ)+(y−cy)⋅cos(θ)+cy
2. Steps:
o Calculate the midpoint (center of the rectangle).
o Rotate each vertex around the midpoint using the rotation matrix.
3. Vertices Representation:
o Rectangles are represented as a list of four points: [(x1, y1), (x2, y2), ...].
4. Visualization:

o The program uses matplotlib to draw:


▪ The original rectangle as a solid blue line.
▪ The rotated rectangle as a dashed red line.
▪ The midpoint as a green point.

Output:
• A plot showing the original rectangle and its rotated version.
• You can modify the rectangle vertices and rotation angle to test with different inputs

6. Write a Program to clip a line using Liang Barsky Method.

The Liang-Barsky algorithm is an efficient method for line clipping against a rectangular clipping window.
Below is a Python implementation of the Liang-Barsky method to clip a line against a rectangular clipping
window.

Python Program: Line Clipping Using Liang-Barsky Method


python
Copy code
import matplotlib.pyplot as plt

def liang_barsky(x_min, y_min, x_max, y_max, x1, y1, x2, y2):


"""
Clip a line using the Liang-Barsky algorithm.

Parameters:
x_min, y_min: Bottom-left corner of the clipping window.
x_max, y_max: Top-right corner of the clipping window.
x1, y1, x2, y2: Endpoints of the line.

Returns:
(x1', y1', x2', y2'): The clipped line endpoints if visible, otherwise None.
"""
dx = x2 - x1
dy = y2 - y1

p = [-dx, dx, -dy, dy]


q = [x1 - x_min, x_max - x1, y1 - y_min, y_max - y1]
u1, u2 = 0.0, 1.0 # Parametric values

for i in range(4):
if p[i] == 0: # Parallel line
if q[i] < 0:
return None # Line is outside the clipping window
else:
t = q[i] / p[i]
if p[i] < 0: # Entering segment
u1 = max(u1, t)
else: # Exiting segment
u2 = min(u2, t)
if u1 > u2:
return None # Line is completely outside

# Calculate clipped line coordinates


clipped_x1 = x1 + u1 * dx
clipped_y1 = y1 + u1 * dy
clipped_x2 = x1 + u2 * dx
clipped_y2 = y1 + u2 * dy

return clipped_x1, clipped_y1, clipped_x2, clipped_y2

def plot_clipping_window(x_min, y_min, x_max, y_max):


"""Plot the clipping window as a rectangle."""
plt.plot([x_min, x_max, x_max, x_min, x_min],
[y_min, y_min, y_max, y_max, y_min],
'k-', label="Clipping Window")

def plot_line(x1, y1, x2, y2, style, label):

"""Plot a line segment."""


plt.plot([x1, x2], [y1, y2], style, label=label)

# Define the clipping window


x_min, y_min = 2, 2
x_max, y_max = 8, 6

# Define the line to clip


x1, y1 = 1, 1
x2, y2 = 9, 7

# Perform clipping
clipped_line = liang_barsky(x_min, y_min, x_max, y_max, x1, y1, x2, y2)

# Plot the results


plt.figure(figsize=(8, 6))
plot_clipping_window(x_min, y_min, x_max, y_max)

# Plot the original line


plot_line(x1, y1, x2, y2, 'b--', label="Original Line")

# Plot the clipped line


if clipped_line:
clipped_x1, clipped_y1, clipped_x2, clipped_y2 = clipped_line
plot_line(clipped_x1, clipped_y1, clipped_x2, clipped_y2, 'r-', label="Clipped Line")
else:
print("Line is completely outside the clipping window.")

# Configure the plot


plt.title("Line Clipping Using Liang-Barsky Algorithm")
plt.xlabel("X")
plt.ylabel("Y")

plt.legend()
plt.grid(True)
plt.axis('equal')
plt.show()

Explanation:
1. Parameters:
o The clipping rectangle is defined by (x_min, y_min) and (x_max, y_max).
o The line is defined by its endpoints (x1, y1) and (x2, y2).
2. Algorithm:
o The algorithm calculates parametric values (u1 and u2) that determine the portions of the
line inside the clipping window.
o If u1 > u2, the line is completely outside the clipping window.
3. Edge Cases:
o If the line is parallel to a clipping boundary and outside, it is rejected.
o If the line lies entirely within the clipping window, it is returned unchanged.
4. Visualization:
o The clipping window is plotted as a rectangle.
o The original line is plotted as a dashed blue line.
o The clipped line is plotted as a solid red line.
Output:
• A graphical representation of the original line, the clipping window, and the clipped line (if it is
partially or fully inside the window).

7. Write a Program to implement Standard Perspective Projection in 3- Dimensions.

The Standard Perspective Projection transforms 3D coordinates into 2D coordinates by simulating a


perspective view. Here's a Python implementation of the Perspective Projection for 3D points.

Python Program: Standard Perspective Projection


python
Copy code
import numpy as np
import matplotlib.pyplot as plt

def perspective_projection(points, d):


"""
Apply standard perspective projection to 3D points.

Parameters:
points (np.array): A 3D array of shape (n, 3), where each row is (x, y, z).
d (float): The distance of the viewer (projection plane) from the origin.

Returns:
np.array: A 2D array of shape (n, 2) containing the projected points.
"""
projected_points = []
for x, y, z in points:
if z != 0: # Avoid division by zero
xp = (d * x) / z
yp = (d * y) / z
projected_points.append((xp, yp))
else:
projected_points.append((np.inf, np.inf)) # Undefined points
return np.array(projected_points)

# Define 3D points to project (a cube as an example)


cube_points = np.array([
[1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1], # Front face
[1, 1, 3], [1, -1, 3], [-1, -1, 3], [-1, 1, 3] # Back face
])

# Define edges of the cube for plotting


edges = [
(0, 1), (1, 2), (2, 3), (3, 0), # Front face

(4, 5), (5, 6), (6, 7), (7, 4), # Back face
(0, 4), (1, 5), (2, 6), (3, 7) # Connecting edges
]

# Distance of the projection plane


d=2

# Perform perspective projection


projected_points = perspective_projection(cube_points, d)

# Plot original 3D points and their projection in 2D


plt.figure(figsize=(8, 6))

# Draw the edges of the projected cube


for edge in edges:
p1, p2 = edge
x_coords = [projected_points[p1][0], projected_points[p2][0]]
y_coords = [projected_points[p1][1], projected_points[p2][1]]
plt.plot(x_coords, y_coords, 'b-')
# Plot projected points
plt.scatter(projected_points[:, 0], projected_points[:, 1], color='red', label="Projected Points")

# Configure plot
plt.title("3D to 2D Perspective Projection")
plt.xlabel("X (projected)")
plt.ylabel("Y (projected)")
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True)
plt.legend()
plt.axis('equal')

plt.show()

Explanation:
1. Perspective Projection Formula:
o For a 3D point (x,y,z)(x, y, z)(x,y,z), the projection onto a 2D plane at distance ddd from the
origin is given by: x′=d⋅xz,y′=d⋅yzx' = \frac{d \cdot x}{z}, \quad y' = \frac{d \cdot y}{z}x′=zd⋅x
,y′=zd⋅y
o zzz represents the depth of the point in the scene.
2. 3D Object:
o A cube is used as an example, represented by its 8 vertices.
3. Edges:
o The edges of the cube are defined to connect its vertices for visualization.
4. Projection Plane:
o The plane is at a distance ddd from the origin. Larger ddd values reduce the perspective
effect, making the projection closer to orthographic.
5. Visualization:
o The program uses matplotlib to plot the 2D projection of the cube.
o Red points represent the projected vertices, and blue lines connect them to visualize the
cube structure.

Output:
• A 2D plot showing the perspective projection of the cube.
• You can adjust the d value, cube dimensions, or add other 3D shapes to see different perspective
effects.

8. Write a Program to implement Parallel Projection in 3- Dimensions.

Here is a Python program to implement Parallel Projection in 3D. In parallel projection, the lines projecting
from the object to the viewing plane are parallel, preserving the relative proportions of the object.

Python Program: Parallel Projection


python
Copy code
import numpy as np
import matplotlib.pyplot as plt

def parallel_projection(points, projection_plane='xy'):


"""
Apply parallel projection to 3D points onto a 2D plane.

Parameters:
points (np.array): A 3D array of shape (n, 3), where each row is (x, y, z).
projection_plane (str): The plane onto which to project ('xy', 'xz', or 'yz').

Returns:
np.array: A 2D array of shape (n, 2) containing the projected points.
"""
if projection_plane == 'xy':
return points[:, :2] # Keep x, y; discard z
elif projection_plane == 'xz':
return points[:, [0, 2]] # Keep x, z; discard y
elif projection_plane == 'yz':
return points[:, [1, 2]] # Keep y, z; discard x
else:
raise ValueError("Invalid projection plane. Choose 'xy', 'xz', or 'yz'.")

# Define 3D points to project (a cube as an example)


cube_points = np.array([
[1, 1, 1], [1, -1, 1], [-1, -1, 1], [-1, 1, 1], # Front face
[1, 1, 3], [1, -1, 3], [-1, -1, 3], [-1, 1, 3] # Back face
])

# Define edges of the cube for plotting


edges = [
(0, 1), (1, 2), (2, 3), (3, 0), # Front face
(4, 5), (5, 6), (6, 7), (7, 4), # Back face
(0, 4), (1, 5), (2, 6), (3, 7) # Connecting edges

# Select the projection plane ('xy', 'xz', or 'yz')


projection_plane = 'xy' # Change this to 'xz' or 'yz' for other views

# Perform parallel projection


projected_points = parallel_projection(cube_points, projection_plane)

# Plot the original 3D object in the 2D projection


plt.figure(figsize=(8, 6))

# Draw the edges of the projected cube


for edge in edges:
p1, p2 = edge
x_coords = [projected_points[p1][0], projected_points[p2][0]]
y_coords = [projected_points[p1][1], projected_points[p2][1]]
plt.plot(x_coords, y_coords, 'b-')

# Plot projected points


plt.scatter(projected_points[:, 0], projected_points[:, 1], color='red', label="Projected Points")

# Configure the plot


plt.title(f"3D to 2D Parallel Projection on the {projection_plane.upper()} Plane")
plt.xlabel("X" if projection_plane in ['xy', 'xz'] else "Y")
plt.ylabel("Y" if projection_plane == 'xy' else "Z")
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.grid(True)
plt.legend()
plt.axis('equal')
plt.show()

Explanation:
1. Parallel Projection:
o Projects a 3D point (x,y,z)(x, y, z)(x,y,z) onto a specified 2D plane by dropping one coordinate:
▪ For XY plane: Retain x,yx, yx,y and discard zzz.
▪ For XZ plane: Retain x,zx, zx,z and discard yyy.
▪ For YZ plane: Retain y,zy, zy,z and discard xxx.
2. 3D Object:
o The program uses a cube represented by its 8 vertices.
3. Edges:
o The cube's edges are defined to connect its vertices, making the structure visible.
4. Projection Planes:
o The user can choose the projection plane ('xy', 'xz', or 'yz') to view the projection from
different perspectives.
5. Visualization:
o The program uses matplotlib to plot the projected 2D view of the cube.
o Red points represent the projected vertices, and blue lines connect them to visualize the
structure.

Output:
• A 2D plot of the 3D cube projected onto the specified plane.
• You can modify the projection_plane variable to switch between XY, XZ, and YZ projections.

9. Write a Program to implement Digital Clock.

Here’s a Python program to implement a Digital Clock using the tkinter library. The program continuously
updates the current time and displays it in a graphical window.

Python Program: Digital Clock


python
Copy code
import tkinter as tk
from time import strftime

def update_time():
"""Update the time displayed on the clock."""
current_time = strftime('%H:%M:%S %p') # Format: Hour:Minute:Second AM/PM
label.config(text=current_time)
label.after(1000, update_time) # Update every second

# Create the main window


window = tk.Tk()
window.title("Digital Clock")
window.geometry("400x200")
window.configure(bg="black")

# Configure the label to display the clock


label = tk.Label(window, font=("Arial", 50), bg="black", fg="cyan")
label.pack(expand=True)

# Start the clock


update_time()

# Run the GUI event loop


window.mainloop()

Explanation:
1. strftime:
o The strftime('%H:%M:%S %p') function formats the current time:
▪ %H for 24-hour format hours.
▪ %M for minutes.
▪ %S for seconds.
▪ %p for AM/PM.
2. label.after(1000, update_time):
o Calls the update_time function every 1000 milliseconds (1 second) to refresh the clock.
3. GUI with tkinter:
o The main window (window) displays the time using a Label widget.

o The label's font, background (bg), and foreground (fg) colors are set for a digital clock
appearance.
4. Customizations:
o Change font, bg, and fg to modify the clock’s appearance.
o Adjust geometry("400x200") for window size.

Output:
• A graphical window with a digital clock showing the current time in the format HH:MM:SS AM/PM.
• The time updates in real-time every second.

10. Write a Program to draw animation using increasing circles filled with different colors and patterns
Here’s a Python program that creates an animation of increasing circles filled with different colors and
patterns. This is achieved using the matplotlib library's animation feature.

Python Program: Animation of Increasing Circles


python
Copy code
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
# Create a figure and axis for the animation
fig, ax = plt.subplots(figsize=(6, 6))
ax.set_xlim(-50, 50)
ax.set_ylim(-50, 50)
ax.set_aspect('equal')
ax.axis('off')

# List of colors and patterns


colors = ['red', 'blue', 'green', 'orange', 'purple', 'yellow']
patterns = ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']

# List to store the drawn circles

circles = []

def update(frame):
"""Update function for animation frames."""
global circles
# Clear existing circles
for circle in circles:
circle.remove()

# Create new set of circles


circles = []
for i in range(6): # Number of circles
radius = (frame + i * 10) % 50 + 5 # Modulo to keep radii in range
color = colors[i % len(colors)]
pattern = patterns[i % len(patterns)]
circle = plt.Circle((0, 0), radius, color=color, alpha=0.5, fill=True, hatch=pattern)
circles.append(circle)
ax.add_artist(circle)
# Create the animation
ani = animation.FuncAnimation(fig, update, frames=np.arange(0, 100, 1), interval=100)

# Display the animation


plt.show()

Explanation:
1. Figure Setup:
o A matplotlib figure and axes are created with equal aspect ratio to ensure circles appear
correctly.
2. Animation:
o The FuncAnimation class from matplotlib.animation is used to animate the circle growth.
o update function recalculates and redraws circles for each frame.

3. Circle Attributes:
o Radius increases over time using (frame + i * 10) % 50 + 5.
o Colors and patterns alternate from predefined lists using modulo indexing.
4. Hatching Patterns:
o Patterns like /, |, +, etc., add a visual effect to the circle fills.
5. Customizations:
o Adjust the colors and patterns list for variety.
o Change interval (in milliseconds) to control animation speed.
o Modify the frames range for animation duration.

Output:
• Animated circles expand from the center, filled with alternating colors and patterns.
• The radii reset after reaching a maximum value, creating a looping effect.

You might also like