0% found this document useful (0 votes)
58 views32 pages

CG & IP Lab Manual-21CSL66

This pdf as almost 12 projects

Uploaded by

reddysaiu55
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)
58 views32 pages

CG & IP Lab Manual-21CSL66

This pdf as almost 12 projects

Uploaded by

reddysaiu55
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/ 32

Sri Devaraj Urs Educational Trust ® , Kolar.

R. L. JALAPPA INSTITUTE OF TECHNOLOGY


(Affiliated to VTU, Belagavi & Recognized by AICTE, New Delhi)
Kodigehalli, Doddaballapur-561203, Bangalore Rural District
Estd:2001

Department of Computer Science and


Engineering

Lab Manual
Laboratory: Computer Graphics and Image
Processing Laboratory
Subject Code: 21CSL66
For IV Semester CSE
Prepared By:

Mr. Rajesh Kumar J


Asst. Professor
Dept. of CS&E, RLJIT, Doddaballapur

Mr. Basavaraj S Pol


Asst. Professor
Dept. of CS&E, RLJIT, Doddaballapur
Vision of the Institution
To be a premier institution by imparting quality Technical education, Professional Training and
Research
Mission of the Institution
M1: To provide an outstanding Teaching, Learning and Research environment through Innovative
Practices in Quality Education.
M2: Develop Leaders with a high level of Professionalism to have a career in the Industry, Zeal
for Higher Education, focus on Entrepreneurial and societal activities.

Vision of the Department


To empower the students with recent trends and technologies in the area of computer science
and engineering to excel in the global competitive world.

Mission of the Department


M1: To develop skills in the field of Computer Science and Engineering in different domains to
focus on developing the essential competencies and qualities to meet the industry prospects.
M2: To ensure quality research and Innovations to cater the needs of industry, Government and
Society imparting the Entrepreneurship and Consultancy silks.

Program Educational Objectives (PEOs)

PEO1: Our Graduates will have prospective carrier in the IT industry.


PEO2: Our Graduates will exhibit high level of Professionalism and Leadership skills in work
Environment.
PEO3: Our Graduates will pursue higher studies, Research and focus on Entrepreneurship.

Program Specific Outcomes (PSOs)

PSO1: Students will have the knowledge of Software, Hardware, Network Models, Algorithms
and various Computer Programming Languages.
PSO2: Students will be able to develop computer applications in the areas related to Artificial
Intelligence, Machine Learning and IOT for efficient design of computer based system.
PSO3: Students will be able to develop Database Applications.

Programme Outcomes (PO)


1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader
in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
Engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
12. Life -long learning: Recognize the need for, and have the preparation and ability to engage
in independent and life -long learning in the broadest context of technological change.
VI Semester

COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY


Course Code 21CSL66 CIE Marks 50
Teaching Hours/Week (L:T:P: S) 0:0:2:0 SEE Marks 50
Total Hours of Pedagogy 24 Total Marks 100
Credits 1 Exam Hours 03
Course Objectives:
CLO 1: Demonstrate the use of Open GL.
CLO 2: Demonstrate the different geometric object drawing using openGL CLO 3: Demonstration
of 2D/3D transformation on simple objects.
CLO 4: Demonstration of lighting effects on the created objects. CLO 5: Demonstration of Image
processing operations on image/s.
Sl. No. Practise Programs
 Installation of OpenGL /OpenCV/ Python and required headers
 Simple programs using OpenGL (Drawing simple geometric object like line, circle,
rectangle, square)
 Simple programs using OpenCV (operation on an image/s)
PART A
List of problems for which student should develop program and execute in the Laboratory
using openGL/openCV/ Python
1. Develop a program to draw a line using Bresenham’s line drawing technique
2. Develop a program to demonstrate basic geometric operations on the 2D object
3. Develop a program to demonstrate basic geometric operations on the 3D object
4. Develop a program to demonstrate 2D transformation on basic objects
5. Develop a program to demonstrate 3D transformation on 3D objects
6. Develop a program to demonstrate Animation effects on simple objects.
7. Write a Program to read a digital image. Split and display image into 4 quadrants, up, down,
right and left.
8. Write a program to show rotation, scaling, and translation on an image.
Read an image and extract and display low-level features such as edges, textures using
9.
filtering techniques.
10. Write a program to blur and smoothing an image.
11. Write a program to contour an image.
12. Write a program to detect a face/s in an image.
PART B
Practical Based Learning
Student should develop a mini project and it should be demonstrate in the laboratory
examination, Some of the projects are listed and it is not limited to:
 Recognition of License Plate through Image Processing
 Recognition of Face Emotion in Real-Time
 Detection of Drowsy Driver in Real-Time
 Recognition of Handwriting by Image Processing
 Detection of Kidney Stone
 Verification of Signature
 Compression of Color Image
 Classification of Image Category
 Detection of Skin Cancer
 Marking System of Attendance using Image Processing
 Detection of Liver Tumor
 IRIS Segmentation
 Detection of Skin Disease and / or Plant Disease
 Biometric Sensing System .
 Projects which helps to formers to understand the present developments in
agriculture.
 Projects which helps high school/college students to understand the scientific
problems.
 Simulation projects which helps to understand innovations in science and
technology
Course Outcome (Course Skill Set)
At the end of the course the student will be able to:

CO 1: Use openGL /OpenCV for the development of mini Projects.


CO 2: Analyze the necessity mathematics and design required to demonstrate basic geometric
transformation techniques.
C0 3: Demonstrate the ability to design and develop input interactive techniques.
C0 4: Apply the concepts to Develop user friendly applications using Graphics and IP concepts.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is
50%. The minimum passing mark for the CIE is 40% of the maximum marks (20 marks). A student
shall be deemed to have satisfied the academic requirements and earned the credits allotted to each
course. The student has to secure not less than 35% (18 Marks out of 50) in the semester-end
examination (SEE).

Continuous Internal Evaluation (CIE):

CIE marks for the practical course is 50 Marks.

The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
 Each experiment to be evaluated for conduction with observation sheet and record write-up.
Rubrics for the evaluation of the journal/write-up for hardware/software experiments designed
by the faculty who is handling the laboratory session and is made known to students at the
beginning of the practical session.
 Record should contain all the specified experiments in the syllabus and each experiment write-
up will be evaluated for 10 marks.
 Total marks scored by the students are scaled downed to 30 marks (60% of maximum marks).
 Weightage to be given for neatness and submission of record/write-up on time.

 Department shall conduct 02 tests for 100 marks, the first test shall be conducted after the 8th

week of the semester and the second test shall be conducted after the 14th week of the semester.
 In each test, test write-up, conduction of experiment, acceptable result, and procedural
knowledge will carry a weightage of 60% and the rest 40% for viva-voce.
 The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
Rubrics suggested in Annexure-II of Regulation book
 The average of 02 tests is scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and average marks of two
tests is the total CIE marks scored by the student.
Semester End Evaluation (SEE):

 SEE marks for the practical course is 50 Marks.


 SEE shall be conducted jointly by the two examiners of the same institute, examiners are
appointed by the University
 All laboratory experiments are to be included for practical examination.
 (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer script to
be strictly adhered to by the examiners. OR based on the course requirement evaluation rubrics
shall be decided jointly by examiners.
 Students can pick one question (experiment) from the questions lot prepared by the internal
/external examiners jointly.
 Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners.
 General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure
and result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for
100 marks and scored marks shall be scaled down to 50 marks (however, based on course type,
rubrics shall be decided by the examiners)
 Students can pick one experiment from the questions lot of PART A with equal choice to all
the students in a batch.
 PART B : Student should develop a mini project and it should be demonstrated in the
laboratory examination (with report and presentation).
 Weightage of marks for PART A is 60% and for PART B is 40%. General rubrics suggested to
be followed for part A and part B.
 Change of experiment is allowed only once (in part A) and marks allotted to the procedure part to
be made zero.
The duration of SEE is 03 hours.
Suggested Learning Resources:
1. Donald Hearn & Pauline Baker: Computer Graphics with OpenGL Version,3rd/4th
Edition, Pearson Education,2011
2. James D Foley, Andries Van Dam, Steven K Feiner, John F Huges Computer graphics
with
OpenGL: Pearson education
Weblinks and Video Lectures (e-Resources):
1. https://nptel.ac.in/courses/106/106/106106090/
2. https://nptel.ac.in/courses/106/102/106102063/
3. https://nptel.ac.in/courses/106/103/106103224/
4. https://nptel.ac.in/courses/106/102/106102065/
5. https://www.tutorialspoint.com/opencv/
6. https://medium.com/analytics-vidhya/introduction-to-computer-vision-opencv-in-python-
fb722e805e8b
Sl. No. INDEX Page No
Develop a program to draw a line using Bresenham’s line drawing
1 1- 2
technique.
Develop a program to demonstrate basic geometric operations on the 2D
2 3-5
object.
Develop a program to demonstrate basic geometric operations on the 3D
3 6-7
object.

4 Develop a program to demonstrate 2D transformation on basic objects. 8-9

5 Develop a program to demonstrate 3D transformation on 3D objects. 10 - 12

6 Develop a program to demonstrate Animation effects on simple objects. 13 - 14

Write a Program to read a digital image. Split and display image into 4
7 15 - 16
quadrants, up, down, right and left.

8 Write a program to show rotation, scaling, and translation on an image. 17 - 18

Read an image and extract and display low-level features such as edges,
9 19 - 20
textures using filtering techniques.

10 Write a program to blur and smoothing an image. 21 - 22

11 Write a program to contour an image. 23 - 24

12 Write a program to detect a face/s in an image. 25


Computer Graphics and Image Processing Laboratory 21CSL66

Program 01: Develop a program to draw a line using Bresenham’s line drawing technique.

import turtle

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


# Calculate the deltas
dx = abs(x2 - x1)
dy = abs(y2 - y1)

# Determine the step direction for each axis


x_step = 1 if x1 < x2 else -1
y_step = 1 if y1 < y2 else -1

# Initialize the error term


error = 2 * dy - dx

# Initialize the line points


line_points = []

# Start at the first point


x, y = x1, y1

# Draw the line


for _ in range(dx + 1):
# Add the current point to the line
line_points.append((x, y))

# Update the error term and adjust the coordinates


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.speed(0) # Fastest drawing speed

x1, y1 = 100, 100


x2, y2 = 400, 300

Dept., of CS&E, RLJIT Page 1


Computer Graphics and Image Processing Laboratory 21CSL66

line_points = bresenham_line(x1, y1, x2, y2)

# Draw the line


turtle.penup()
turtle.goto(x1, y1)
turtle.pendown()
for x, y in line_points:
turtle.goto(x, y)

turtle.exitonclick()

OUTPUT:

Dept., of CS&E, RLJIT Page 2


Computer Graphics and Image Processing Laboratory 21CSL66

Program 02: Develop a program to demonstrate basic geometric operations on the 2D object.

import turtle
import math

# Set up the turtle screen


screen = turtle.Screen()
screen.bgcolor("white")

# Create a turtle instance


t = turtle.Turtle()
t.speed(1) # Set the drawing speed (1 is slowest, 10 is fastest)
t.pensize(2) # Set the pen size

# Define a function to draw a rectangle


def draw_rectangle(x, y, width, height, color):
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)

# Define a function to draw a circle


def draw_circle(x, y, radius, color):
t.penup()
t.goto(x, y - radius)
t.pendown()
t.color(color)
t.circle(radius)

# Define a function to translate a 2D object


def translate(x, y, dx, dy):
t.penup()
t.goto(x + dx, y + dy)
t.pendown()

# Define a function to rotate a 2D object


def rotate(x, y, angle):

Dept., of CS&E, RLJIT Page 3


Computer Graphics and Image Processing Laboratory 21CSL66

t.penup()
t.goto(x, y)
t.setheading(angle)
t.pendown()

# Define a function to scale a 2D object


def scale(x, y, sx, sy):
t.penup()
t.goto(x * sx, y * sy)
t.pendown()

# Draw a rectangle
draw_rectangle(-200, 0, 100, 50, "blue")

# Translate the rectangle


translate(-200, 0, 200, 0)
draw_rectangle(0, 0, 100, 50, "blue")

# Rotate the rectangle


rotate(0, 0, 45)
draw_rectangle(0, 0, 100, 50, "blue")

# Scale the rectangle


scale(0, 0, 2, 2)
draw_rectangle(0, 0, 100, 50, "blue")

# Draw a circle
draw_circle(100, 100, 50, "red")

# Translate the circle


translate(100, 100, 200, 0)
draw_circle(300, 100, 50, "red")

# Rotate the circle


rotate(300, 100, 45)
draw_circle(300, 100, 50, "red")

# Scale the circle


scale(300, 100, 2, 2)
draw_circle(600, 200, 50, "red")

# Keep the window open until it's closed

Dept., of CS&E, RLJIT Page 4


Computer Graphics and Image Processing Laboratory 21CSL66

turtle.done()

OUTPUT:

Dept., of CS&E, RLJIT Page 5


Computer Graphics and Image Processing Laboratory 21CSL66

Program 03: Develop a program to demonstrate basic geometric operations on the 3D object.

from vpython import canvas, box, cylinder, vector, color, rate

# Create a 3D canvas
scene = canvas(width=800, height=600, background=color.white)

# Define a function to draw a cuboid


def draw_cuboid(pos, length, width, height, color):
cuboid = box(pos=vector(*pos), length=length, width=width, height=height, color=color)
return cuboid

# Define a function to draw a cylinder


def draw_cylinder(pos, radius, height, color):
cyl = cylinder(pos=vector(*pos), radius=radius, height=height, color=color)
return cyl

# Define a function to translate a 3D object


def translate(obj, dx, dy, dz):
obj.pos += vector(dx, dy, dz)

# Define a function to rotate a 3D object


def rotate(obj, angle, axis):
obj.rotate(angle=angle, axis=vector(*axis))

# Define a function to scale a 3D object


def scale(obj, sx, sy, sz):
obj.size = vector(obj.size.x * sx, obj.size.y * sy, obj.size.z * sz)

# Draw a cuboid
cuboid = draw_cuboid((-2, 0, 0), 2, 2, 2, color.blue)

# Translate the cuboid


translate(cuboid, 4, 0, 0)

# Rotate the cuboid


rotate(cuboid, angle=45, axis=(0, 1, 0))

# Scale the cuboid


scale(cuboid, 1.5, 1.5, 1.5)

# Draw a cylinder

Dept., of CS&E, RLJIT Page 6


Computer Graphics and Image Processing Laboratory 21CSL66

cylinder = draw_cylinder((2, 2, 0), 1, 10, color.red)

# Translate the cylinder


translate(cylinder, 0, -2, 0)

# Rotate the cylinder


rotate(cylinder, angle=30, axis=(1, 0, 0))

# Scale the cylinder


scale(cylinder, 1.5, 1.5, 1.5)

# Keep the 3D scene interactive


while True:
rate(30) # Set the frame rate to 30 frames per second

OUTPUT:

Dept., of CS&E, RLJIT Page 7


Computer Graphics and Image Processing Laboratory 21CSL66

Program 04: Develop a program to demonstrate 2D transformation on basic objects.

import cv2
import numpy as np

# Define the dimensions of the canvas


canvas_width = 500
canvas_height = 500

# Create a blank canvas


canvas = np.ones((canvas_height, canvas_width, 3), dtype=np.uint8) * 255

# Define the initial object (a square)


obj_points = np.array([[100, 100], [200, 100], [200, 200], [100, 200]], dtype=np.int32)

# Define the transformation matrices


translation_matrix = np.float32([[1, 0, 100], [0, 1, 50]])
rotation_matrix = cv2.getRotationMatrix2D((150, 150), 45, 1)
scaling_matrix = np.float32([[1.5, 0, 0], [0, 1.5, 0]])

# Apply transformations
translated_obj = np.array([np.dot(translation_matrix, [x, y, 1])[:2] for x, y in obj_points], dtype=np.int32)
rotated_obj = np.array([np.dot(rotation_matrix, [x, y, 1])[:2] for x, y in translated_obj], dtype=np.int32)
scaled_obj = np.array([np.dot(scaling_matrix, [x, y, 1])[:2] for x, y in rotated_obj], dtype=np.int32)

# Draw the objects on the canvas


cv2.polylines(canvas, [obj_points], True, (0, 0, 0), 2)
cv2.polylines(canvas, [translated_obj], True, (0, 255, 0), 2)
cv2.polylines(canvas, [rotated_obj], True, (255, 0, 0), 2)
cv2.polylines(canvas, [scaled_obj], True, (0, 0, 255), 2)

# Display the canvas


cv2.imshow("2D Transformations", canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()

Dept., of CS&E, RLJIT Page 8


Computer Graphics and Image Processing Laboratory 21CSL66

OUTPUT:

Dept., of CS&E, RLJIT Page 9


Computer Graphics and Image Processing Laboratory 21CSL66

Program 05: Develop a program to demonstrate 3D transformation on 3D objects.

import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np

# Initialize Pygame
pygame.init()

# Set up the display


display_width = 800
display_height = 600
display = pygame.display.set_mode((display_width, display_height), DOUBLEBUF | OPENGL)
pygame.display.set_caption("3D Transformations")

# Set up OpenGL
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
glMatrixMode(GL_PROJECTION)
gluPerspective(45, (display_width / display_height), 0.1, 50.0)
glMatrixMode(GL_MODELVIEW)

# Define the 3D object (a cube)


vertices = np.array([
[-1, -1, -1],
[1, -1, -1],
[1, 1, -1],
[-1, 1, -1],
[-1, -1, 1],
[1, -1, 1],
[1, 1, 1],
[-1, 1, 1]
], dtype=np.float32)

edges = np.array([
[0, 1], [1, 2], [2, 3], [3, 0],
[4, 5], [5, 6], [6, 7], [7, 4],
[0, 4], [1, 5], [2, 6], [3, 7]
], dtype=np.uint32)

Dept., of CS&E, RLJIT Page 10


Computer Graphics and Image Processing Laboratory 21CSL66

# Set up the transformation matrices


translation_matrix = np.eye(4, dtype=np.float32)
translation_matrix[3, :3] = [0, 0, -5]

rotation_matrix = np.eye(4, dtype=np.float32)

scaling_matrix = np.eye(4, dtype=np.float32)


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:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Clear the display


glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

# Apply transformations
glLoadIdentity()
glMultMatrixf(translation_matrix)
glRotatef(angle, 1, 1, 0)
glMultMatrixf(rotation_matrix)
glMultMatrixf(scaling_matrix)

# Draw the 3D object


glBegin(GL_LINES)
for edge in edges:
for vertex in edge:
glVertex3fv(vertices[vertex])
glEnd()

# Update the rotation angle


angle += 1

# Swap the front and back buffers


pygame.display.flip()

Dept., of CS&E, RLJIT Page 11


Computer Graphics and Image Processing Laboratory 21CSL66

# Quit Pygame
pygame.quit()

OUTPUT:

Dept., of CS&E, RLJIT Page 12


Computer Graphics and Image Processing Laboratory 21CSL66

Program 06: Develop a program to demonstrate Animation effects on simple objects.

import pygame
import random

# Initialize Pygame
pygame.init()

# Set up the display


screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Animation Effects")

# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Define object properties


num_objects = 10
objects = []
for _ in range(num_objects):
x = random.randint(50, screen_width - 50)
y = random.randint(50, screen_height - 50)
radius = random.randint(10, 30)
color = random.choice([RED, GREEN, BLUE])
speed_x = random.randint(-5, 5)
speed_y = random.randint(-5, 5)
objects.append({"x": x, "y": y, "radius": radius, "color": color, "speed_x": speed_x, "speed_y": speed_y})

# Main loop
running = True
clock = pygame.time.Clock()
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

Dept., of CS&E, RLJIT Page 13


Computer Graphics and Image Processing Laboratory 21CSL66

# Clear the screen


screen.fill(WHITE)

# Update and draw objects


for obj in objects:
# Move the object
obj["x"] += obj["speed_x"]
obj["y"] += obj["speed_y"]

# Bounce off the edges


if obj["x"] - obj["radius"] < 0 or obj["x"] + obj["radius"] > screen_width:
obj["speed_x"] = -obj["speed_x"]
if obj["y"] - obj["radius"] < 0 or obj["y"] + obj["radius"] > screen_height:
obj["speed_y"] = -obj["speed_y"]

# Draw the object


pygame.draw.circle(screen, obj["color"], (obj["x"], obj["y"]), obj["radius"])

# Update the display


pygame.display.flip()
clock.tick(60) # Limit the frame rate to 60 FPS

# Quit Pygame
pygame.quit()

OUTPUT:

Dept., of CS&E, RLJIT Page 14


Computer Graphics and Image Processing Laboratory 21CSL66

Program-07: Write a Program to read a digital image. Split and display image into 4 quadrants, up,
down, right and left.

import cv2

# Function to split the image into four quadrants


def split_image(image):
height, width, _ = image.shape
half_height = height // 2
half_width = width // 2

# Split the image into four quadrants


top_left = image[:half_height, :half_width]
top_right = image[:half_height, half_width:]
bottom_left = image[half_height:, :half_width]
bottom_right = image[half_height:, half_width:]

return top_left, top_right, bottom_left, bottom_right

# Function to display images


def display_images(images, window_names):
for img, name in zip(images, window_names):
cv2.imshow(name, img)

print("Press any key to terminate.")


cv2.waitKey(0)
cv2.destroyAllWindows()

# Read the image


image_path = "image.jpg" # Replace "image.jpg" with the path to your image
image = cv2.imread(image_path)

if image is None:
print("Failed to load the image.")
else:
# Split the image into quadrants
top_left, top_right, bottom_left, bottom_right = split_image(image)

# Display the quadrants


display_images([top_left, top_right, bottom_left, bottom_right], ["Top Left", "Top Right", "Bottom Left",
"Bottom Right"])

Dept., of CS&E, RLJIT Page 15


Computer Graphics and Image Processing Laboratory 21CSL66

OUTPUT:

Dept., of CS&E, RLJIT Page 16


Computer Graphics and Image Processing Laboratory 21CSL66

Program-08: Write a program to show rotation, scaling, and translation on an image.

import cv2
import numpy as np

# Load the image


image_path = "image.jpg" # Replace with the path to your image
img = cv2.imread(image_path)

# Get the image dimensions


height, width, _ = img.shape

# Define the transformation matrices


rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), 45, 1) # Rotate by 45 degrees
scaling_matrix = np.float32([[1.5, 0, 0], [0, 1.5, 0]]) # Scale by 1.5x
translation_matrix = np.float32([[1, 0, 100], [0, 1, 50]]) # Translate by (100, 50)

# Apply transformations
rotated_img = cv2.warpAffine(img, rotation_matrix, (width, height))
scaled_img = cv2.warpAffine(img, scaling_matrix, (int(width*1.5), int(height*1.5)))
translated_img = cv2.warpAffine(img, translation_matrix, (width, height))

# Display the original and transformed images


cv2.imshow("Original Image", img)
cv2.imshow("Rotated Image", rotated_img)
cv2.imshow("Scaled Image", scaled_img)
cv2.imshow("Translated Image", translated_img)

# Wait for a key press and then close all windows


cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT:

Dept., of CS&E, RLJIT Page 17


Computer Graphics and Image Processing Laboratory 21CSL66

Dept., of CS&E, RLJIT Page 18


Computer Graphics and Image Processing Laboratory 21CSL66

Program-09: Read an image and extract and display low-level features such as edges, textures using
filtering techniques.

import cv2
import numpy as np

# Load the image


image_path = "flower.jpg" # Replace with the path to your image
img = cv2.imread(image_path)

# Convert the image to grayscale


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Edge detection
edges = cv2.Canny(gray, 100, 200) # Use Canny edge detector

# Texture extraction
kernel = np.ones((5, 5), np.float32) / 25 # Define a 5x5 averaging kernel
texture = cv2.filter2D(gray, -1, kernel) # Apply the averaging filter for texture extraction

# Display the original image, edges, and texture


cv2.imshow("Original Image", img)
cv2.imshow("Edges", edges)
cv2.imshow("Texture", texture)

# Wait for a key press and then close all windows


cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT:

Dept., of CS&E, RLJIT Page 19


Computer Graphics and Image Processing Laboratory 21CSL66

Dept., of CS&E, RLJIT Page 20


Computer Graphics and Image Processing Laboratory 21CSL66

Program-10: Write a program to blur and smoothing an image.

import cv2

# Load the image


image = cv2.imread('flower.jpg')

# Gaussian Blur
gaussian_blur = cv2.GaussianBlur(image, (5, 5), 0)

# Median Blur
median_blur = cv2.medianBlur(image, 5)

# Bilateral Filter
bilateral_filter = cv2.bilateralFilter(image, 9, 75, 75)

# Display the original and processed images


cv2.imshow('Original Image', image)
cv2.imshow('Gaussian Blur', gaussian_blur)
cv2.imshow('Median Blur', median_blur)
cv2.imshow('Bilateral Filter', bilateral_filter)

# Wait for a key press to close the windows


cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT:

Dept., of CS&E, RLJIT Page 21


Computer Graphics and Image Processing Laboratory 21CSL66

Dept., of CS&E, RLJIT Page 22


Computer Graphics and Image Processing Laboratory 21CSL66

Program-11:Write a program to contour an image.

import cv2
import numpy as np

# Load the image


image = cv2.imread('flower.jpg')

# Convert the image to grayscale


gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply binary thresholding


ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# Find contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Create a copy of the original image to draw contours on


contour_image = image.copy()

# Draw contours on the image


cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2)

# Display the original and contour images


cv2.imshow('Original Image', image)
cv2.imshow('Contours', contour_image)

# Wait for a key press to close the windows


cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT:

Dept., of CS&E, RLJIT Page 23


Computer Graphics and Image Processing Laboratory 21CSL66

Dept., of CS&E, RLJIT Page 24


Computer Graphics and Image Processing Laboratory 21CSL66

Program-12: Write a program to detect a face/s in an image.

import cv2

# Load the cascade classifier for face detection


face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Load the image


image = cv2.imread('people.jpeg')

# Convert the image to grayscale


gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the grayscale image


faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))

# Draw rectangles around the detected faces


for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

# Display the image with detected faces


cv2.imshow('Face Detection', image)

# Wait for a key press to close the window


cv2.waitKey(0)
cv2.destroyAllWindows()

OUTPUT:

Dept., of CS&E, RLJIT Page 25

You might also like