CG&IP Lab Manual
CG&IP Lab Manual
Subject Code:21CSL66
Program-01
Program
import turtle
dx = abs(x2 - x1)
dy = abs(y2 - y1)
error = 2 * dy - dx
line_points = []
Search Creators…. Page 1
21CSL66 | COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY|
x, y = x1, y1
line_points.append((x, y))
if error > 0:
y += y_step
error -= 2 * dx
error += 2 * dy
x += x_step
return line_points
# Example usage
turtle.setup(500, 500)
turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
for x, y in line_points:
turtle.goto(x, y)
turtle.exitonclick()
Output
Explaination:
1. The bresenham_line function takes four arguments: x1, y1, x2, and y2, which represent the
starting and ending points of the line segment.
2. Inside the function, it calculates the deltas (dx and dy) between the starting and ending
points, and determines the step direction (x_step and y_step) for each axis.
3. It initializes the error term (error) and an empty list (line_points) to store the coordinates
of the line points.
4. The function then enters a loop that iterates dx + 1 times, where in each iteration:
5. It appends the current point (x, y) to the line_points list.
6. It updates the error term (error) and adjusts the coordinates of x and y based on the
Bresenham's line algorithm.
7. After the loop, the function returns the line_points list containing the coordinates of the
line points.
8. In the example usage section, the code sets up a turtle graphics window, defines the starting
and ending points of the line segment (x1, y1, x2, y2), calls the bresenham_line function
to get the line points, and then draws the line segment by moving the turtle to each point in
the line_points list.
9. The turtle.exitonclick() function keeps the graphics window open until the user clicks on
it, allowing the user to view the drawn line.
Subject Code:21CSL66
Program-02
Program
import turtle
import math
screen = turtle.Screen()
screen.bgcolor("white")
t = turtle.Turtle()
t.penup()
t.goto(x, y)
t.pendown()
t.color(color)
for _ in range(2):
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.penup()
t.goto(x, y - radius)
t.pendown()
t.color(color)
t.circle(radius)
t.penup()
t.pendown()
t.penup()
t.goto(x, y)
t.setheading(angle)
t.pendown()
t.penup()
t.pendown()
# Draw a rectangle
translate(-200, 0, 200, 0)
rotate(0, 0, 45)
scale(0, 0, 2, 2)
# Draw a circle
scale(300, 100, 2, 2)
turtle.done()
Output
Explanation
1. The code starts by importing the necessary modules: turtle for drawing graphics and math
for mathematical operations.
2. A turtle screen is set up with a white background color.
3. A turtle instance t is created, and its speed and pen size are set.
4. Two helper functions draw_rectangle and draw_circle is defined to draw rectangles and
circles, respectively. These functions take the coordinates, dimensions (width, height, or
radius), and color as arguments.
5. Three transformation functions are defined: translate, rotate, and scale. These functions
take the coordinates and transformation parameters (translation distances, rotation angle,
or scaling factors) as arguments and move the turtle's position and orientation
accordingly.
6. The code then demonstrates the use of these functions by drawing and transforming a
rectangle and a circle.
• A rectangle is drawn at (-200, 0) with a width of 100 and a height of 50 in blue
color.
• The rectangle is translated 200 units to the right, and a new rectangle is drawn at
(0, 0).
• The rectangle is rotated by 45 degrees, and a new rectangle is drawn.
• The rectangle is scaled by a factor of 2 in both dimensions, and a new rectangle is
drawn.
• A circle is drawn at (100, 100) with a radius of 50 in red color.
• The circle is translated 200 units to the right, and a new circle is drawn at (300,
100).
• The circle is rotated by 45 degrees, and a new circle is drawn.
• The circle is scaled by a factor of 2 in both dimensions, and a new circle is drawn
at (600, 200).
7. Finally, the turtle. done () function is called to keep the window open until it's closed by
the user.
Subject Code:21CSL66
Program-03
Program
# Create a 3D canvas
return cuboid
return cyl
obj.rotate(angle=angle, axis=vector(*axis))
# Draw a cuboid
translate(cuboid, 4, 0, 0)
# Draw a cylinder
translate(cylinder, 0, -2, 0)
while True:
Output
Explainations
Subject Code:21CSL66
Program-04
Program
import cv2
import numpy as np
canvas_width = 500
canvas_height = 500
# Apply transformations
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explainations
1. The code starts by importing the necessary libraries: cv2 for OpenCV and
numpy for numerical operations.
2. It defines the dimensions of the canvas (canvas_width and canvas_height) and
creates a blank white canvas using NumPy.
3. The initial object (a square) is defined as an array of four points (obj_points)
representing the vertices of the square.
4. The transformation matrices are defined:
• translation_matrix: A 2x3 matrix for translation.
• rotation_matrix: A rotation matrix obtained using
cv2.getRotationMatrix2D for rotating around a specified center point
by a given angle.
• scaling_matrix: A 2x3 matrix for scaling.
5. The transformations are applied to the initial object by performing matrix
multiplication with the transformation matrices:
• translated_obj: The object is translated by applying the
translation_matrix.
• rotated_obj: The translated object is rotated by applying the
rotation_matrix.
• scaled_obj: The rotated object is scaled by applying the
scaling_matrix.
6. The original object and the transformed objects (translated, rotated, and
scaled) are drawn on the canvas using cv2.polylines.
7. The canvas with the drawn objects is displayed using cv2.imshow, and the
code waits for a key press (cv2.waitKey(0)) before closing the window.
8. Finally, all windows are closed using cv2.destroyAllWindows().
Subject Code:21CSL66
Program-05
Program
import pygame
import numpy as np
# Initialize Pygame
pygame.init()
display_width = 800
display_height = 600
pygame.display.set_caption("3D Transformations")
# Set up OpenGL
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_MODELVIEW)
vertices = np.array([
[1, 1, -1],
[-1, 1, -1],
[1, 1, 1],
[-1, 1, 1]
], dtype=np.float32)
edges = np.array([
], dtype=np.uint32)
scaling_matrix[0, 0] = 1.5
scaling_matrix[1, 1] = 1.5
scaling_matrix[2, 2] = 1.5
# Main loop
running = True
angle = 0
while running:
if event.type == pygame.QUIT:
running = False
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
Search Creators…. Page 3
21CSL66 | COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY|
# Apply transformations
glLoadIdentity()
glMultMatrixf(translation_matrix)
glRotatef(angle, 1, 1, 0)
glMultMatrixf(rotation_matrix)
glMultMatrixf(scaling_matrix)
glBegin(GL_LINES)
glVertex3fv(vertices[vertex])
glEnd()
angle += 1
pygame.display.flip()
# Quit Pygame
pygame.quit()
Search Creators…. Page 4
21CSL66 | COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY|
Output
Explanation
• Draws the 3D cube by iterating over the edges and vertices, using
glBegin(GL_LINES) and glVertex3fv.
• Increments the rotation angle for the next iteration.
• Swaps the front and back buffers using pygame.display.flip() to display
the rendered scene.
12.After the main loop ends, the code quits Pygame.
Subject Code:21CSL66
Program-06
Program
import pygame
import random
# Initialize Pygame
pygame.init()
screen_width = 800
screen_height = 600
pygame.display.set_caption("Animation Effects")
# Define colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
num_objects = 10
objects = []
for _ in range(num_objects):
speed_x = random.randint(-5, 5)
speed_y = random.randint(-5, 5)
# Main loop
running = True
clock = pygame.time.Clock()
while running:
# Handle events
if event.type == pygame.QUIT:
running = False
screen.fill(WHITE)
obj["x"] += obj["speed_x"]
obj["y"] += obj["speed_y"]
obj["speed_x"] = -obj["speed_x"]
obj["speed_y"] = -obj["speed_y"]
pygame.display.flip()
# Quit Pygame
pygame.quit()
Output
Explanation
1. Imports the required modules: pygame for creating the graphical window and
handling events, and random for generating random values.
2. Initializes Pygame and sets up a window with a width of 800 pixels and a
height of 600 pixels.
3. Defines some colors (BLACK, WHITE, RED, GREEN, BLUE) as RGB
tuples.
4. Initializes a list called objects to store the properties of each circle object. The
properties include the x and y coordinates, radius, color, and velocities
(speed_x and speed_y).
5. Generates num_objects (set to 10) with random positions, radii, colors, and
velocities, and appends them to the objects list.
6. Enters the main loop, which runs until the user closes the window.
7. Inside the main loop:
8. Handles the Pygame event queue, checking for the QUIT event to exit the
loop.
9. Clears the screen by filling it with the WHITE color.
10.Iterates over each object in the objects list:
11.Updates the x and y coordinates of the object based on its velocities.
12.Checks if the object has collided with the edges of the screen. If so, it reverses
the corresponding velocity component (x or y) to make the object bounce off
the edge.
13.Draws the object (circle) on the screen using pygame.draw.circle with the
object's color, position, and radius.
14.Updates the display using pygame.display.flip().
15.Limits the frame rate to 60 frames per second (FPS) using clock.tick(60).
Subject Code:21CSL66
Program-07
7. Write a Program to read a digital image. Split and display image into 4
quadrants, up, down, right and left.
Program
import cv2
import numpy as np
img = cv2.imread(image_path)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation
Subject Code:21CSL66
Program-08
Program
import cv2
import numpy as np
img = cv2.imread(image_path)
# Apply transformations
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation
Subject Code:21CSL66
Program-09
9. Read an image and extract and display low-level features such as edges,
textures using filtering techniques.
Program
import cv2
import numpy as np
img = cv2.imread(image_path)
# Edge detection
# Texture extraction
texture = cv2.filter2D(gray, -1, kernel) # Apply the averaging filter for texture
extraction
cv2.imshow("Edges", edges)
cv2.imshow("Texture", texture)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation
Subject Code:21CSL66
Program-10
Program
import cv2
image = cv2.imread('image/atc.jpg')
# Gaussian Blur
# Median Blur
median_blur = cv2.medianBlur(image, 5)
# Bilateral Filter
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation
Subject Code:21CSL66
Program-11
Program
import cv2
import numpy as np
image = cv2.imread('image/atc.jpg')
# Find contours
contour_image = image.copy()
cv2.imshow('Contours', contour_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation
1. The cv2 library is imported from OpenCV, and the numpy library is imported
for numerical operations.
2. The image is loaded using cv2.imread('image/atc.jpg'). Make sure to replace
'image/atc.jpg' with the correct path to your image file.
3. The image is converted to grayscale using cv2.cvtColor(image,
cv2.COLOR_BGR2GRAY). This step is necessary because contour detection
is often performed on grayscale images.
4. Binary thresholding is applied to the grayscale image using
cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV +
cv2.THRESH_OTSU). This operation converts the grayscale image into a
binary image, where pixels are either black or white, based on a threshold
value. The cv2.THRESH_OTSU flag automatically determines the optimal
threshold value using Otsu's method. The cv2.THRESH_BINARY_INV flag
inverts the binary image, so that foreground objects become white and the
background becomes black.
5. The contours are found in the binary image using cv2.findContours(thresh,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE). The
cv2.RETR_EXTERNAL flag retrieves only the extreme outer contours, and
cv2.CHAIN_APPROX_SIMPLE compresses the contour data by
approximating it with a simplified polygon.
6. A copy of the original image is created using contour_image = image.copy().
This copy will be used to draw the contours on.
7. The contours are drawn on the contour image using
cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2). The -1
argument indicates that all contours should be drawn, the (0, 255, 0) argument
specifies the color (green in this case), and the 2 argument specifies the
thickness of the contour lines.
8. The original image and the contour image are displayed using cv2.imshow().
9. The script waits for a key press (cv2.waitKey(0)) before closing the windows.
10.Finally, all windows are closed using cv2.destroyAllWindows().
Subject Code:21CSL66
Program-12
Program
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
image = cv2.imread('image/face.jpeg')
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
Explanation
(0, 255, 0) argument specifies the color (green in this case), and the 2
argument specifies the thickness of the rectangle lines.
11.The image with the detected faces and rectangles is displayed using
cv2.imshow('Face Detection', image).
12.The script waits for a key press (cv2.waitKey(0)) before closing the window.
13.Finally, the window is closed using cv2.destroyAllWindows().