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

CGI Manual @vtuupdates Com

Uploaded by

Rahul Tr
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)
17 views

CGI Manual @vtuupdates Com

Uploaded by

Rahul Tr
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/ 37

COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

PART A
Program 1: Develop a program to draw a line using Bresenham’s line drawing technique

Program Objective:
• creation of 2D objects
• Implement GLU and GLUT functions
 To have the detailed knowledge of the graphics Bresenham’s line algorithm.

#include<GL/glut.h>
#include<stdio.h>
int x1,x2,y1,y2; void
myInit()
{ glClearColor(0.0,0.0,0.0,0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); gluOrtho2D(0,500,0,500);
}
void draw_pixel(int x,int y)
{
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd(); }
void draw_line(int x1,int x2,int y1,int y2)
{ int dx,dy,i,e; int
incx,incy,inc1,inc2;
int x,y;
dx=x2-x1;
dy=y2-y1;
if(dx<0) dx=-dx;
if(dy<0) dy=-dy;
incx=1;
if(x2<x1) incx=-
1; incy=1;
if(y2<y1) incy=-
1; x=x1; y=y1;
if(dx>dy) {
draw_pixel(x,y);
e=2*dy-dx;
inc1=2*(dy-dx);
inc2=2*dy;
for(i=0;i<dx;i++)
{
if(e>=0) {
y+=incy;
e+=inc1; } else
e+=inc2;
x+=incx;
draw_pixel(x,y);

www.vtuupdates.com Page 1
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

} } else {
draw_pixel(x,y);
e=2*dx-dy;
inc1=2*(dx-dy);
inc2=2*dx;
for(i=0;i<dy;i++)
{ if(e>=0) {
x+=incx;
e+=inc1; } else
e+=inc2;
y+=incy;
draw_pixel(x,y);
}
}
} void
myDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
draw_line(x1,x2,y1,y2); glFlush(); }
int main(int argc,char **argv)
{
printf("enter x1,x2,y1,y2\n");
scanf("%d%d%d%d",&x1,&x2,&y1,&y2);
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0,0);
glutCreateWindow("win");
glutDisplayFunc(myDisplay);
myInit();
glEnable(GL_DEPTH_TEST);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}

RUN:
g++ 1.cpp -lglut -lGL –lGLU

./a.out

OUTPUT:

www.vtuupdates.com Page 2
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

s
Program Outcome:
 Ability to Design and develop 2D objects for different graphics applications.
 Use matrix algebra in computer graphics and implement Brenham's line algorithm.
 Analyze and evaluate the use of openGL methodss in practical applications of 2D
representations.

www.vtuupdates.com Page 3
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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


object

Program Objective: 
creation of 2D objects
• Create 2D objects with basic transformation operations like translation, rotation, scaling.
• Use mathematical and theoretical principles i.e. transformation matrices of computer
graphics to draw and translate, rotate, scaled object.

#include <GL/glut.h>
#include <iostream>

float rectangleWidth = 100.0f;


float rectangleHeight = 50.0f;

float translateX = 0.0f; float


translateY = 0.0f;

float rotateAngle = 0.0f;

float scaleX = 1.0f; float


scaleY = 1.0f;

void init() {
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-300.0, 300.0, -300.0, 300.0);
}

void drawRectangle() {
glPushMatrix();
glTranslatef(translateX, translateY, 0.0);
glRotatef(rotateAngle, 0.0, 0.0, 1.0);
glScalef(scaleX, scaleY, 1.0);

glColor3f(0.0, 0.0, 0.0);


glBegin(GL_POLYGON);
glVertex2f(-rectangleWidth / 2, -rectangleHeight / 2);
glVertex2f(rectangleWidth / 2, -rectangleHeight / 2);
glVertex2f(rectangleWidth / 2, rectangleHeight / 2);
glVertex2f(-rectangleWidth / 2, rectangleHeight / 2); glEnd();

glPopMatrix();
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

www.vtuupdates.com Page 4
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

drawRectangle();
glFlush();
}
void keyboard(unsigned char key, int x, int y) {
switch (key) { case 't':
translateX += 10.0f;
translateY += 10.0f;
break;
case 'r':
rotateAngle += 10.0f;
break;
case 's':
scaleX += 0.1f;
scaleY += 0.1f;
break;
}
glutPostRedisplay();
}

int main(int argc, char** argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600);
glutInitWindowPosition(100, 100);
glutCreateWindow("2D object Geometric Operations in OpenGL");

init();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);

glutMainLoop();

return 0;
}

RUN:

g++ 2.cpp -lglut -lGL –lGLU

./a.out

This program creates a rectangle using OpenGL and demonstrates three basic geometric
operations:
1. Translation: Press 't' to translate the rectangle by 10 units in both the x and y directions.
2. Rotation: Press 'r' to rotate the rectangle by 10 degrees clockwise around its center.
3. Scaling: Press 's' to scale the rectangle by 0.1 in both the x and y directions.

www.vtuupdates.com Page 5
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

Compile and run this program, then press the respective keys to perform the geometric
operations. You should see the rectangle change accordingly on the screen.

OUTPUT:

www.vtuupdates.com Page 6
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• creation of 3D objects
• Create 3D object with basic transformation operations like translation, rotation, scaling.
• Use mathematical and theoretical principles i.e. transformation matrices of computer graphics to
draw and translate, rotate, scaled object.

#include<GL/glut.h>
#include<stdio.h>
GLfloat vertices[][3]={{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0},{1.0,1.0,-1.0},{-1.0,1.0,-1.0},{-1.0,-
1.0,1.0},{1.0,-1.0,1.0},{1.0,1.0,1.0},{-1.0,1.0,1.0}};

GLfloat
colors[][3]={{0.0,0.0,0.0},{0.0,0.0,1.0},{0.0,1.0,0.0},{0.0,1.0,1.0},{1.0,0.0,0.0},{1.0,0.0,1.0},{1.
0,1.0,0.0},{1.0,1.0,1.0}};
static GLfloat theta[]={0.0,0.0,0.0};
static GLint axis=2; static
GLdouble viewer[]={0,0,5};
void polygon(int a,int b,int c,int d)
{
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd(); }
void colorcube()
{ polygon(0,3,2,1);
polygon(2,3,7,6);
polygon(1,2,6,5);
polygon(0,4,5,1);
polygon(4,5,6,7);
polygon(0,3,7,4);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glLoadIdentity();
glRotatef(theta[0],1.0,0.0,0.0);
glRotatef(theta[1],0.0,1.0,0.0);
glRotatef(theta[2],0.0,0.0,1.0);
colorcube(); glFlush();
glutSwapBuffers();
}

www.vtuupdates.com Page 7
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

void spincube()
{ theta[axis]+=2.0;
if(theta[axis]>360.0)
theta[axis]-=360.0;
glutPostRedisplay();
}
void mouse(int btn,int state,int x,int y)
{
if(btn==GLUT_LEFT_BUTTON&&state==GLUT_DOWN) axis=0;
if(btn==GLUT_MIDDLE_BUTTON&&state==GLUT_DOWN) axis=1;
if(btn==GLUT_RIGHT_BUTTON&&state==GLUT_DOWN)
axis=2; spincube(); }
void myreshape(int w,int h)
{
glViewport(0,0,w,h); glMatrixMode(GL_PROJECTION);
glLoadIdentity(); if(w<=h)
glOrtho(-2.0,2.0,-2.0*(GLfloat)h/(GLfloat)w,2.0*(GLfloat)h/(GLfloat)w,-10.0,10.0); else
glOrtho(-2.0*(GLfloat)w/(GLfloat)h,2.0*(GLfloat)w/(GLfloat)h,-2.0,2.0,-10.0,10.0);
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay();
}
int main(int argc,char**argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB|GLUT_DEPTH);
glutCreateWindow("3D object Geometric Operations in OpenGL ");
glutReshapeFunc(myreshape); glutDisplayFunc(display);
glutIdleFunc(spincube); glutMouseFunc(mouse);
glEnable(GL_DEPTH_TEST); glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop(); return
0;
}

RUN:
g++ 3.cpp -lglut -lGL –lGLU

./a.out

OUTPUT:

www.vtuupdates.com Page 8
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

Program Outcome:

• Ability to Design and develop 3D objects for different graphics applications.


• Use matrix algebra in computer graphics and implement fundamental transformations involved
in transformation operation.
• Ability to draw objects using basic objects like points and lines.
• Analyze and evaluate the use of openGL methods in practical applications of 3D representations.

www.vtuupdates.com Page 9
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• creation of 2D objects
• Create 2D objects with basic transformation operations like translation, rotation, scaling.
• Use mathematical and theoretical principles i.e. transformation matrices of computer
graphics to draw and rotate the color cube object.
• Use matrix algebra in computer graphics and implement fundamental algorithms and
transformations involved in viewing models.

#include <GL/glut.h>
#include <cmath>

// Object properties
struct Object {
float x; float
y; float size;
};

// Initial positions and sizes of objects


Object rectangle = { -50.0f, 50.0f, 100.0f };
Object triangle = { 50.0f, 50.0f, 100.0f };
Object circle = { 0.0f, -50.0f, 50.0f };

// Transformation properties
float translateX = 0.0f; float
translateY = 0.0f; float
rotateAngle = 0.0f; float
scaleX = 1.0f; float scaleY
= 1.0f;

void init() {
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-300.0, 300.0, -300.0, 300.0);
}

void drawRectangle(float x, float y, float size) {


glPushMatrix(); glTranslatef(x, y, 0.0);
glRotatef(rotateAngle, 0.0, 0.0, 1.0);
glScalef(scaleX, scaleY, 1.0);

glColor3f(0.0, 0.0, 0.0);


glBegin(GL_POLYGON);
glVertex2f(-size / 2, -size / 2);
glVertex2f(size / 2, -size / 2); glVertex2f(size
/ 2, size / 2); glVertex2f(-size / 2, size / 2);
glEnd(); glPopMatrix();

www.vtuupdates.com Page 10
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

void drawTriangle(float x, float y, float size) {


glPushMatrix(); glTranslatef(x, y, 0.0);
glRotatef(rotateAngle, 0.0, 0.0, 1.0);
glScalef(scaleX, scaleY, 1.0);

glColor3f(0.0, 0.0, 0.0);


glBegin(GL_TRIANGLES);
glVertex2f(0.0, size / 2);
glVertex2f(-size / 2, -size / 2);
glVertex2f(size / 2, -size / 2); glEnd();

glPopMatrix();
}

void drawCircle(float x, float y, float size) {


const int numSegments = 50;
const float angleIncrement = 2.0f * 3.14159f / numSegments;

glPushMatrix(); glTranslatef(x, y,
0.0); glRotatef(rotateAngle, 0.0, 0.0,
1.0);
glScalef(scaleX, scaleY, 1.0);

glColor3f(0.0, 0.0, 0.0);


glBegin(GL_POLYGON);
for (int i = 0; i < numSegments; ++i) {
float angle = i * angleIncrement;
glVertex2f(cos(angle) * size / 2, sin(angle) * size / 2);
}
glEnd();

glPopMatrix();
}

void display() {
glClear(GL_COLOR_BUFFER_BIT);

drawRectangle(rectangle.x + translateX, rectangle.y + translateY, rectangle.size);


drawTriangle(triangle.x + translateX, triangle.y + translateY, triangle.size);
drawCircle(circle.x + translateX, circle.y + translateY, circle.size);

glFlush();
}

void keyboard(unsigned char key, int x, int y) {


switch (key) {

www.vtuupdates.com Page 11
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

case 't':
translateX += 10.0f;
translateY += 10.0f;
break;
case 'r':
rotateAngle += 10.0f;
break;
case 's':
scaleX += 0.1f;
scaleY += 0.1f; break;
}
glutPostRedisplay();
}

int main(int argc, char** argv) {


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(600, 600); glutInitWindowPosition(100,
100);
glutCreateWindow("2D Transformations in OpenGL");

init();
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);

glutMainLoop();

return 0;
}

RUN:
g++ 4.cpp -lglut -lGL –lGLU

./a.out

www.vtuupdates.com Page 12
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:

Program Outcome:

• Ability to Design and develop 2D objects for different graphics applications.


• Use matrix algebra in computer graphics and implement fundamental transformations
involved in viewing models.
• Analyze and evaluate the use of openGL methods in practical applications of 2D
representations.

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

Program Objective:

www.vtuupdates.com Page 13
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

• creation of 3D objects
• Create 3D objects with basic transformation operations like translation, rotation, scaling.
• Use mathematical and theoretical principles i.e. transformation matrices of computer
graphics to draw and rotate the color cube object.
• Use matrix algebra in computer graphics and implement fundamental algorithms and
transformations involved in viewing models.

#include <GL/glut.h>
#include <iostream>

// Global variables int


width = 800; int height =
600; GLfloat translateX =
0.0f;
GLfloat translateY = 0.0f;
GLfloat rotationX = 0.0f;
GLfloat rotationY = 0.0f;
GLfloat scale = 1.0f;

// Function to draw a cube void


drawCube() {
glBegin(GL_QUADS);

// Front face glColor3f(1.0f,


0.0f, 0.0f); // Red glVertex3f(-
0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);

// Back face
glColor3f(0.0f, 1.0f, 0.0f); // Green
glVertex3f(-0.5f, -0.5f, -0.5f); glVertex3f(-
0.5f, 0.5f, -0.5f); glVertex3f(0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, -0.5f);

// Top face glColor3f(0.0f,


0.0f, 1.0f); // Blue glVertex3f(-
0.5f, 0.5f, -0.5f); glVertex3f(-
0.5f, 0.5f, 0.5f); glVertex3f(0.5f,
0.5f, 0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);

// Bottom face
glColor3f(1.0f, 1.0f, 0.0f); // Yellow glVertex3f(-
0.5f, -0.5f, -0.5f); glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);

www.vtuupdates.com Page 14
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

// Right face
glColor3f(1.0f, 0.0f, 1.0f);
// Magenta
glVertex3f(0.5f, -0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, -0.5f);
glVertex3f(0.5f, 0.5f, 0.5f);
glVertex3f(0.5f, -0.5f, 0.5f);

// Left face
glColor3f(0.0f, 1.0f, 1.0f);
// Cyan
glVertex3f(-0.5f, -0.5f, -0.5f);
glVertex3f(-0.5f, -0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, 0.5f);
glVertex3f(-0.5f, 0.5f, -0.5f);

glEnd();
}

// Function to handle display void


display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

// Apply transformations
//glTranslatef(0.0f, 0.0f, -3.0f);
glTranslatef(translateX, 0.0f, -3.0f);
glTranslatef(0.0f, translateY, -3.0f);
glRotatef(rotationX, 1.0f, 0.0f, 0.0f);
glRotatef(rotationY, 0.0f, 1.0f, 0.0f);
glScalef(scale, scale, scale);

// Draw cube
drawCube();

glutSwapBuffers();
}

// Function to handle keyboard events void


keyboard(unsigned char key, int x, int y) {
switch (key) {
case 'x':
rotationX += 5.0f;

www.vtuupdates.com Page 15
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

break; case
'X': rotationX -=
5.0f;
break;
case 'z':
rotationY += 5.0f;
break;
case 'Z':
rotationY -= 5.0f;
break;
case '+': scale
+= 0.1f; break;
case '-': if
(scale > 0.1f)
scale -= 0.1f;
break; case 't':
translateX += 0.5f;
break; case 'T':
translateX -= 0.5f;
break; case 'y':
translateY += 0.5f;
break; case 'Y':
translateY -= 0.5f;
break;
case 27: // Escape key to exit
exit(0);
break;
}

glutPostRedisplay(); // Trigger a redraw


}

// Function to initialize OpenGL void


initializeOpenGL(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("Geometric Operations in 3D");

glEnable(GL_DEPTH_TEST);
glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // White background

glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (float)width / (float)height, 1.0f, 100.0f);

glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
}

www.vtuupdates.com Page 16
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

// Main function int main(int


argc, char** argv) {
initializeOpenGL(argc, argv);
glutMainLoop();
return 0;
}

RUN:
g++ 5.cpp -lglut -lGL –lGLU

./a.out
OUTPUT:

www.vtuupdates.com Page 17
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• creation of animation effects on objects

#include <GL/glut.h>
#include <math.h>
#include <stdlib.h>

const double TWO_PI = 6.2831853; GLsizei


winWidth = 500, winHeight = 500;
GLuint regHex;
static GLfloat rotTheta = 0.0;

// Initial display window size.


// Define name for display list.
class scrPt { public: GLint x,
y;
};

static void init(void)


{ scrPt hexVertex;
GLdouble hexTheta;
GLint k; glClearColor(1.0,
1.0, 1.0, 0.0);
/* Set up a display list for a red regular hexagon.
* Vertices for the hexagon are six equally spaced
* points around the circumference of a circle.
*/
regHex = glGenLists(1);
glNewList(regHex, GL_COMPILE);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POLYGON); for(k = 0; k <
6; k++) { hexTheta = TWO_PI * k / 6;
hexVertex.x = 150 + 100 * cos(hexTheta);
hexVertex.y = 150 + 100 * sin(hexTheta);
glVertex2i(hexVertex.x, hexVertex.y);
} glEnd( );
glEndList( );
}

void displayHex(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix( );
glRotatef(rotTheta, 0.0, 0.0, 1.0);
glCallList(regHex);
glPopMatrix( );

www.vtuupdates.com Page 18
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

glutSwapBuffers( ); glFlush(
);
}

void rotateHex(void)
{ rotTheta += 3.0;
if(rotTheta > 360.0)
rotTheta -= 360.0;
glutPostRedisplay( );
}
void winReshapeFcn(GLint newWidth, GLint newHeight)
{
glViewport(0, 0,(GLsizei) newWidth,(GLsizei) newHeight);
glMatrixMode(GL_PROJECTION);
glLoadIdentity( ); gluOrtho2D(-320.0,
320.0, -320.0, 320.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity( );
glClear(GL_COLOR_BUFFER_BIT);
}
void mouseFcn(GLint button, GLint action, GLint x, GLint y)
{ switch(button) { case
GLUT_MIDDLE_BUTTON:
// Start the rotation.
if(action == GLUT_DOWN)
glutIdleFunc(rotateHex); break;
case GLUT_RIGHT_BUTTON:
// Stop the rotation.
if(action == GLUT_DOWN)
glutIdleFunc(NULL);
break;
default:
break;
}
}

int main(int argc, char** argv)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(150, 150);
glutInitWindowSize(winWidth, winHeight);
glutCreateWindow("Animation Example");
init( );
glutDisplayFunc(displayHex);
glutReshapeFunc(winReshapeFcn); glutMouseFunc(mouseFcn);
glutMainLoop( ); return 0; }

www.vtuupdates.com Page 19
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

RUN:
g++ 6.cpp -lglut -lGL –lGLU

./a.out

OUTPUT:

Program Outcome:

• Applying animation effects on objects.

www.vtuupdates.com Page 20
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• Implement CV2 and numpy packages

# Load the image


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

# Get the height and width of the


image h, w, channels = img.shape
half_width = w//2 half_height = h//2

# Split the image into four quadrants


TopLeft_quadrant = img[:half_height, :half_width]
TopRight_quadrant = img[:half_height, half_width:]
BottomLeft_quadrant = img[half_height:, :half_width]
BottomRight_quadrant = img[half_height:, half_width:]

# Display the canvas


cv2.imshow('originalImage',original)
cv2.imshow('TopLeft_Quadrant', TopLeft_quadrant)
cv2.imshow('TopRight_Quadrant', TopRight_quadrant)
cv2.imshow('BottomLeft_Quadrant', BottomLeft_quadrant)
cv2.imshow('BottomRight_Quadrant', BottomRight_quadrant)

cv2.waitKey(0)
cv2.destroyAllWindows()

www.vtuupdates.com Page 21
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:

Program Outcome:

• Ability to read a digital image. Split and display image into 4 quadrants, up, down, right
and left
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

8: Write a program to show rotation, scaling, and translation on an image

Program Objective:

• Implement CV2 and numpy packages


• Implement rotation, scaling, and translation on an image

import cv2
import numpy as np

# Load the image


image_path = "atc.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()

www.vtuupdates.com Page 23
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:

Program Outcome:

• Ability to show rotation, translation and scaling on an image.


COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• Implement CV2 and numpy packages


• Implement edges, textures using filtering techniques.

import cv2
import numpy as np

# Load the image


image_path = "atc.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()

www.vtuupdates.com Page 25
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:

Program Outcome:

• Ability to read an image and extract and display low-level features such as edges, textures
using filtering techniques.
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• Implement CV2 and numpy packages


• Implement blur and smoothing an image

import cv2

# Load the image image =


cv2.imread('atc.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()

www.vtuupdates.com Page 27
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

Program 11: Write a program to contour an image.

Program Objective:

• Implement CV2 and numpy packages  Implement contour an


image.

import cv2
import numpy as np

# Load the image


image = cv2.imread('atc.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()

www.vtuupdates.com Page 29
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:

Program Outcome:

• Able to contour an image


• Contours can be explained simply as a curve joining all the continuous points (along the
boundary), having same color or intensity. The contours are a useful tool for shape analysis
and object detection and recognition. For better accuracy, use binary images.
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

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

Program Objective:

• Implement CV2 and numpy packages


• Implement 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('face.jpg')

# 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()

www.vtuupdates.com Page 31
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

OUTPUT:

Program Outcome:
• Able to detect a face in any given image  Step 1: Import the OpenCV Package.
• Step 2: Read the Image.
• Step 3: Convert the Image to Grayscale.
• Step 4: Load the Classifier.
• Step 5: Perform the Face Detection.
• Step 6: Drawing a Bounding Box.
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66
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)

www.vtuupdates.com Page 33
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66
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 writeup.
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

www.vtuupdates.com Page 34
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66
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

www.vtuupdates.com Page 35
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66

Viva questions and answers


1. What is Computer Graphics?
Computer graphics are graphics created using computers and, more generally, the representation
and manipulation of image data by a computer.

2. What is OpenGL?
OpenGL is the most extensively documented 3D graphics API (Application Pro-gram Interface)
to date. It is used to create Graphics.

3. What is GLUT?
The OpenGL Utility Toolkit (GLUT) is a library of utilities for OpenGL programs, which
primarily perform system-level I/O with the host operating system.

4. What are the applications of Computer Graphics?


Gaming Industry, Animation Industry and Medical Image Processing Industries. The sum total of
these industries is a Multi Billion Dollar Market. Jobs will continue to increase in this arena in the
future.

5. What is a Pixel?
In digital imaging, a pixel (or picture element) is a single point in a raster image. The Pixel is the
smallest addressable screen element; it is the smallest unit of picture which can be controlled. Each
Pixel has its address. The address of Pixels corresponds to its coordinate. Pixels are normally
arranged in a 2-dimensional grid, and are often represented using dots or squares.

6.What is Graphical User Interface?


A graphical user interface (GUI) is a type of user interface item that allows people to interact with
programs in more ways than typing such as computers; hand-held devices such as MP3 Players,
Portable Media Players or Gaming devices; household appliances and o-ce equipment with images
rather than text commands.

7.What support for OpenGL does Open,Net,FreeBSD or Linux provide?


The X Windows implementation, XFree86 4.0, includes support for OpenGL using Mesa or the
OpenGL Sample Implementation. XFree86 is released under the XFree86 license.
http://www.xfree86.org/

8.What is the AUX library?


The AUX library was developed by SGI early in OpenGL's life to ease creation of small OpenGL
demonstration programs. It's currently neither supported nor maintained. Developing OpenGL
programs using AUX is strongly discouraged. Use the GLUT in-stead. It's more exible and
powerful and is available on a wide range of platforms. Very important: Don't use AUX. Use GLUT
instead.

9.How does the camera work in OpenGL?

www.vtuupdates.com Page 36
COMPUTER GRAPHICS AND IMAGE PROCESSING LABORATORY 21CSL66
As far as OpenGL is concerned, there is no camera. More specically, the camera is always located
at the eye space coordinate (0., 0., 0.). To give the appearance of moving the camera, your OpenGL
application must move the scene with the inverse of the camera transformation.

10.What is Microsoft Visual Studio?


Microsoft Visual Studio is an integrated development environment (IDE) for devel-oping windows
applications. It is the most popular IDE for developing windows applications or windows based
software.

11.What does the .gl or .GL le format have to do with OpenGL?


gl les have nothing to do with OpenGL, but are sometimes confused with it. .gl is a le format for
images, which has no relationship to OpenGL.

12.How do we make shadows in OpenGL?


There are no individual routines to control neither shadows nor an OpenGL state for shadows.
However, code can be written to render shadows.

13.What is the use of Glutinit?


void glutInit(int *argcp, char **argv); glutInit will initialize the GLUT library and negotiate a
session with the window system. During this process, glutInit may cause the termination of the
GLUT program with an error message to the user if GLUT cannot be properly initialized.

14.Describe the usage of glutMainLoop? void glutMainLoop(void); glutMainLoop enters the


GLUT event processing loop. This routine should be called at most once in a GLUT program. Once
called, this routine will never return. It will call as necessary any callbacks that have been
registered.

15.What is image processing in Python?


Python enables image processing through libraries like OpenCV, PIL, and scikit-image for
diverse applications.

16.Which is the famous image processing Python?


OpenCV is a popular and powerful image processing library widely used for computer vision
applications.

17.List some application of OpenCV?


Some of the applications of OpenCV are object detection, face recognition, medical diagnosis,
etc.

18.Which method of opencv is used to read image?


The cv2.imread() method of the Imgcodecs class is used in OpenCV to read an image.

19.How many types of image filters available in OpenCV ?


There are two types of image filters available in OpenCV: 1) Linear filter 2) Non-linear filter

www.vtuupdates.com Page 37

You might also like