0% found this document useful (0 votes)
24 views11 pages

CGLABMANUALNEW

Uploaded by

krao44802
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)
24 views11 pages

CGLABMANUALNEW

Uploaded by

krao44802
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/ 11

2.

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


#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
int b[4][4]={{100,100},{100,200},{200,200},{200,100}};
void translate(float tx,float ty)
{
for (int i=0;i<8;i++)
{
b[i][0]=b[i][0]+tx;
b[i][1]=b[i][1]+ty;
}
}
void rotate(float angle)
{
float r=angle*M_PI/180;
for (int i=0;i<8;i++)
{
b[i][0]=b[i][0]*cos(r)-b[i][1]*sin(r);
b[i][1]=b[i][1]*sin(r)+b[i][0]*cos(r);
}
}

void scaling(float sx,float sy)


{
for (int i=0;i<8;i++)
{
b[i][0]=b[i][0]*sx;
b[i][1]=b[i][1]*sy;
}
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);
glBegin(GL_POLYGON);
for(int i=0;i<4;i++)
glVertex2i(b[i][0],b[i][1]);
glEnd();
glFlush();
char option;
printf("enter the option");
scanf("%c",&option);
switch(option)
{
case 't':translate(20,20);break;
case 's':scaling(2,2);break;
case 'r':rotate(-45);break;
default:
printf("please enter the coorect option");
}
}
void main(int argc,char ** argv)
{
glutInit(&argc,argv);
glutCreateWindow("new window");
glClearColor(0.0,0.0,0.0,0.0);
glutDisplayFunc(display);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,500,0,500);
glutMainLoop();
}

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


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

float cubeVertices[8][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}
};

void drawCube() {
glBegin(GL_QUADS);
int faces[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 3, 7, 4}, {1, 2, 6, 5}, {3, 2, 6, 7}, {0, 1, 5, 4}};
for (int i = 0; i < 6; ++i)
for (int j = 0; j < 4; ++j)
glVertex3fv(cubeVertices[faces[i][j]]);
glEnd();
}

void applyTranslation(float tx, float ty, float tz) {


for (int i = 0; i < 8; ++i) {
cubeVertices[i][0] += tx;
cubeVertices[i][1] += ty;
cubeVertices[i][2] += tz;
}
}

void applyRotation(float angle, char axis) {


float rad = angle * M_PI / 180.0;
for (int i = 0; i < 8; ++i) {
float x = cubeVertices[i][0], y = cubeVertices[i][1], z = cubeVertices[i][2];
if (axis == 'x') {
cubeVertices[i][1] = y * cos(rad) - z * sin(rad);
cubeVertices[i][2] = y * sin(rad) + z * cos(rad);
} else if (axis == 'y') {
cubeVertices[i][0] = x * cos(rad) + z * sin(rad);
cubeVertices[i][2] = -x * sin(rad) + z * cos(rad);
} else if (axis == 'z') {
cubeVertices[i][0] = x * cos(rad) - y * sin(rad);
cubeVertices[i][1] = x * sin(rad) + y * cos(rad);
}
}
}

void applyScaling(float sx, float sy, float sz) {


for (int i = 0; i < 8; ++i) {
cubeVertices[i][0] *= sx;
cubeVertices[i][1] *= sy;
cubeVertices[i][2] *= sz;
}
}

void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
drawCube();
glFlush();

int option;
printf("\nChoose Transformation:\n1. Translation\n2. Rotation\n3. Scaling\n4. Exit\nEnter
your choice: ");
scanf("%d", &option);

float tx, ty, tz, angle, sx, sy, sz;


char axis;
switch (option) {
case 1:
applyTranslation(0.1, 0.1, 0.1);
break;
case 2:
applyRotation(45,'y');
break;
case 3:
applyScaling(0.5,0.5,0.5);
break;
case 4:
exit(0);
break;
default:
printf("Invalid option!\n");
}

glutPostRedisplay();
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("3D Object Transformations");
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, 1.0, 1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -5.0);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
4. Develop a program to demonstrate 2D transformation on basic objects
#include<GL/glut.h>
#include<stdio.h>
#include<math.h>
int b[4][4]={{100,100},{100,200},{200,200},{200,100}};
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);
glBegin(GL_POLYGON);
for(int i=0;i<4;i++)
glVertex2i(b[i][0],b[i][1]);
glEnd();
glFlush();
char option;
printf("enter the option");
scanf("%c",&option);
switch(option)
{
case 't':glTranslatef(20,20,0); break;
case 's':glScalef(2,2,1); break;
case 'r':glRotatef(-45,0,0,1); break;
case 'e': exit(0); break;
}
}
void main(int argc,char ** argv)
{
glutInit(&argc,argv);
glutCreateWindow("new window");
glClearColor(0.0,0.0,0.0,0.0);
glutDisplayFunc(display);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,500,0,500);
glutMainLoop();
}
5. Develop a program to demonstrate 3D transformation on 3D objects
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

float cubeVertices[8][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}
};

void drawCube() {
glBegin(GL_QUADS);
int faces[6][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}, {0, 3, 7, 4}, {1, 2, 6, 5}, {3, 2, 6, 7}, {0, 1, 5, 4}};
for (int i = 0; i < 6; ++i)
for (int j = 0; j < 4; ++j)
glVertex3fv(cubeVertices[faces[i][j]]);
glEnd();
}

void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
drawCube();
glFlush();

int option;
printf("\nChoose Transformation:\n1. Translation\n2. Rotation\n3. Scaling\n4. Exit\nEnter
your choice: ");
scanf("%d", &option);

float angleX = 45.0f, angleY = 45.0f, angleZ = 45.0f;


float tx = 0.1f, ty = 0.1f, tz = 0.1f;
float sx = 1.1f, sy = 1.1f, sz = 1.1f;
switch (option) {
case 1:
glTranslatef(tx,ty,tz);
break;
case 2:
glRotatef(angleY, 1.0f, 0.0f, 0.0f);
break;
case 3:
glScalef(sx,sy,sz);
break;
case 4:
exit(0);
break;
default:
printf("Invalid option!\n");
}

glutPostRedisplay();
}

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


glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("3D Object Transformations");
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, 1.0, 1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0, 0.0, -5.0);
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
6. Develop a program to demonstrate Animation effects on simple objects.
#include <GL/glut.h>
// Position of the square
float posX = -0.9f;
float posY = 0.0f;
float speed = 0.01f;

// Initialize OpenGL

// Display callback function


void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
glLoadIdentity(); // Reset transformations

// Move the square


glTranslatef(posX, posY, 0.0f);
glColor3f(1.0,0.0,0.0);
// Draw the square
glBegin(GL_QUADS);
glVertex2f(-0.1f, -0.1f); // Bottom-left
glVertex2f( 0.1f, -0.1f); // Bottom-right
glVertex2f( 0.1f, 0.1f); // Top-right
glVertex2f(-0.1f, 0.1f); // Top-left
glEnd();

glutSwapBuffers(); // Swap the front and back buffers


}

void timer(int value) {


posX += speed; // Update position of the square
if (posX > 1.1f) {
posX = -1.1f; // Reset position to the left side
}
glutPostRedisplay(); // Post a re-paint request to activate display()
glutTimerFunc(16, timer, 0); // Call timer again after 16 milliseconds (approx. 60 FPS)
}

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


glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); // Enable double buffered
glutCreateWindow("2D Moving Square"); // Create window with the given titl

glutDisplayFunc(display); // Register display callback handler for window


re-paint
glutTimerFunc(0, timer, 0); // First timer call immediatel
glutMainLoop(); // Enter the infinite event-processing loop
return 0;
}
7. 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"])

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


import cv2
import numpy as np

# Read the image


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

if image is None:
print("Failed to load the image.")
else:
# Display the original image
cv2.imshow("Original Image", image)

# Rotation
angle = 45 # Rotation angle in degrees
center = (image.shape[1] // 2, image.shape[0] // 2) # Center of rotation
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1.0) # Rotation matrix
rotated_image = cv2.warpAffine(image, rotation_matrix, (image.shape[1],
image.shape[0]))

# Scaling
scale_factor = 0.5 # Scaling factor (0.5 means half the size)
scaled_image = cv2.resize(image, None, fx=scale_factor, fy=scale_factor)

# Translation
translation_matrix = np.float32([[1, 0, 100], [0, 1, -50]]) # Translation matrix (100 pixels
right, 50 pixels up)
translated_image = cv2.warpAffine(image, translation_matrix, (image.shape[1],
image.shape[0]))

# Display the transformed images


cv2.imshow("Rotated Image", rotated_image)
cv2.imshow("Scaled Image", scaled_image)
cv2.imshow("Translated Image", translated_image)

cv2.waitKey(0)
cv2.destroyAllWindows()
9. Read an image and extract and display low-level features such as edges,
textures using filtering techniques.

import cv2
import numpy as np

# Read the image


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

if image is None:
print("Failed to load the image.")
else:
# Display the original image
cv2.imshow("Original Image", image)

# Apply Sobel filter to extract edges


sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)
sobel_edges = cv2.magnitude(sobel_x, sobel_y)
sobel_edges = cv2.normalize(sobel_edges, None, 0, 255, cv2.NORM_MINMAX,
dtype=cv2.CV_8U)

# Display edges extracted using Sobel filter


cv2.imshow("Edges (Sobel Filter)", sobel_edges)

# Apply Laplacian filter to extract edges


laplacian_edges = cv2.Laplacian(image, cv2.CV_64F)
laplacian_edges = cv2.normalize(laplacian_edges, None, 0, 255, cv2.NORM_MINMAX,
dtype=cv2.CV_8U)

# Display edges extracted using Laplacian filter


cv2.imshow("Edges (Laplacian Filter)", laplacian_edges)

# Apply Gaussian blur to extract textures


gaussian_blur = cv2.GaussianBlur(image, (5, 5), 0)

# Display image with Gaussian blur


cv2.imshow("Gaussian Blur", gaussian_blur)

cv2.waitKey(0)
cv2.destroyAllWindows()

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


import cv2

# Read the image


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

if image is None:
print("Failed to load the image.")
else:
# Display the original image
cv2.imshow("Original Image", image)

# Apply blur to the image


blur_kernel_size = (5, 5) # Kernel size for blur filter
blurred_image = cv2.blur(image, blur_kernel_size)

# Display the blurred image


cv2.imshow("Blurred Image", blurred_image)

# Apply Gaussian blur to the image


gaussian_blur_kernel_size = (5, 5) # Kernel size for Gaussian blur filter
gaussian_blurred_image = cv2.GaussianBlur(image, gaussian_blur_kernel_size, 0)

# Display the Gaussian blurred image


cv2.imshow("Gaussian Blurred Image", gaussian_blurred_image)

# Apply median blur to the image


median_blur_kernel_size = 5 # Kernel size for median blur filter (should be odd)
median_blurred_image = cv2.medianBlur(image, median_blur_kernel_size)

# Display the median blurred image


cv2.imshow("Median Blurred Image", median_blurred_image)

cv2.waitKey(0)
cv2.destroyAllWindows()

11. Write a program to contour an image .


import cv2

# Read the image


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

if image is None:
print("Failed to load the image.")
else:
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply adaptive thresholding


_, thresh = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV +
cv2.THRESH_OTSU)

# Find contours in the thresholded image


contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)

# Draw contours on the original image


contour_image = image.copy()
cv2.drawContours(contour_image, contours, -1, (0, 255, 0), 2) # Draw all contours with green
color and thickness 2

# Display the original image with contours


cv2.imshow("Image with Contours", contour_image)

cv2.waitKey(0)
cv2.destroyAllWindows()

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


import cv2

# Load the pre-trained Haar Cascade classifier for face detection


face_cascade = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')

# Read the image


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

if image is None:
print("Failed to load the image.")
else:
# Convert the image to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image


faces = face_cascade.detectMultiScale(gray_image, 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("Image with Detected Faces", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

You might also like