21CSL66
Program 1:Bresenham's Line Algorithm
#include <GL/glut.h>
#include <stdio.h>
int x1, y1, x2, y2;
void draw_pixel(int x, int y)
{
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void bresenhams_line_draw(int x1, int y1, int x2, int y2)
{
int dx = x2 - x1;
int dy = y2 - y1;
int x = x1;
int y = y1;
int p = 2 * dy - dx; // Corrected calculation of p
int twoDy = 2 * dy;
int twoDyMinusDx = 2 * (dy - dx);
draw_pixel(x, y);
while (x < x2)
{
x++;
if (p < 0)
p += twoDy;
else
{
y++;
p += twoDyMinusDx;
}
draw_pixel(x, y);
}
}
void myInit()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 500.0, 0.0, 500.0);
glMatrixMode(GL_MODELVIEW);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
bresenhams_line_draw(x1, y1, x2, y2);
glFlush();
}
int main(int argc, char** argv)
{
printf("Enter Start Points (x1, y1):\n");
scanf_s("%d%d", &x1, &y1);
printf("Enter End Points (x2, y2):\n");
scanf_s("%d%d", &x2, &y2);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Bresenham's Line Drawing");
myInit();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
************************************************************************************************
Program 2: 2D Operations
#include <GL/glut.h>
#include <math.h>
GLfloat vertices[][2] = {
{0.0, 0.5},
{-0.5, -0.5},
{0.5, -0.5}
};
GLfloat angle = 0.0;
GLfloat translateX = 0.0;
GLfloat translateY = 0.0;
GLfloat scaleX = 1.0;
GLfloat scaleY = 1.0;
void display();
void menu(int option);
void createMenu();
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(translateX, translateY, 0);
glRotatef(angle, 0, 0, 1);
glScalef(scaleX, scaleY, 1);
glColor3f(1, 1, 1);
glBegin(GL_TRIANGLES);
for (int i = 0; i < 3; i++) {
glVertex2fv(vertices[i]);
}
glEnd();
glFlush();
}
void menu(int option) {
switch (option) {
case 1:
translateX -= 0.1;
break;
case 2:
translateX += 0.1;
break;
case 3:
translateY -= 0.1;
break;
case 4:
translateY += 0.1;
break;
case 5:
scaleX += 0.1;
scaleY += 0.1;
break;
case 6:
scaleX -= 0.1;
scaleY -= 0.1;
break;
case 7:
angle += 10.0;
if (angle > 360) angle -= 360;
break;
case 8:
angle -= 10.0;
if (angle < 0) angle += 360;
break;
case 9:
angle = 0.0;
translateX = 0.0;
translateY = 0.0;
scaleX = 1.0;
scaleY = 1.0;
break;
case 10:
exit(0);
break;
}
glutPostRedisplay();
}
void createMenu() {
int menuID = glutCreateMenu(menu);
glutAddMenuEntry("Translate left", 1);
glutAddMenuEntry("Translate right", 2);
glutAddMenuEntry("Translate down", 3);
glutAddMenuEntry("Translate up", 4);
glutAddMenuEntry("Scale up", 5);
glutAddMenuEntry("Scale down", 6);
glutAddMenuEntry("Rotate clockwise", 7);
glutAddMenuEntry("Rotate anticlockwise", 8);
glutAddMenuEntry("Reset", 9);
glutAddMenuEntry("Exit", 10);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void init() {
glClearColor(0, 0, 0, 1);
}
void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("2D Geometric Operations");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
createMenu();
init();
glutMainLoop();
return 0;
}
*********************************************************************************************
Program 3:3D Operations
#include <stdlib.h>
#include <GL/glut.h>
// Define cube vertices
GLfloat vertices[][3] = {
{-1, -1, -1},
{1, -1, -1},
{1, 1, -1},
{-1, 1, -1},
{-1, -1, 1},
{1, -1, 1},
{1, 1, 1},
{-1, 1, 1}
};
// Define cube edges
GLint edges[][2] = {
{0, 1},
{1, 2},
{2, 3},
{3, 0},
{4, 5},
{5, 6},
{6, 7},
{7, 4},
{0, 4},
{1, 5},
{2, 6},
{3, 7}
};
// Define rotation angles
GLfloat angleX = 0.0;
GLfloat angleY = 0.0;
GLfloat angleZ = 0.0;
// Define translation offsets
GLfloat translateX = 0.0;
GLfloat translateY = 0.0;
GLfloat translateZ = 0.0;
// Define scaling factors
GLfloat scaleX = 1.0;
GLfloat scaleY = 1.0;
GLfloat scaleZ = 1.0;
// Display function
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Set up perspective projection
gluLookAt(3, 3, 3, 0, 0, 0, 0, 1, 0);
// Apply transformations
glTranslatef(translateX, translateY, translateZ);
glRotatef(angleX, 1, 0, 0);
glRotatef(angleY, 0, 1, 0);
glRotatef(angleZ, 0, 0, 1);
glScalef(scaleX, scaleY, scaleZ);
// Draw cube
glColor3f(1, 1, 1);
glBegin(GL_LINES);
for (int i = 0; i < 12; i++) {
glVertex3fv(vertices[edges[i][0]]);
glVertex3fv(vertices[edges[i][1]]);
}
glEnd();
glutSwapBuffers();
}
// Keyboard function for scaling and translation
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 'w':
translateY += 0.1;
break;
case 's':
translateY -= 0.1;
break;
case 'a':
translateX -= 0.1;
break;
case 'd':
translateX += 0.1;
break;
case 'q':
translateZ += 0.1;
break;
case 'e':
translateZ -= 0.1;
break;
case 'X':
angleX += 5.0f;
break;
case 'x':
angleX -= 5.0f;
break;
case 'Y':
angleY += 5.0f;
break;
case 'y':
angleY -= 5.0f;
break;
case 'Z':
angleZ += 5.0f;
break;
case 'z':
angleZ -= 5.0f;
break;
case '+':
scaleX += 0.1;
scaleY += 0.1;
scaleZ += 0.1;
break;
case '-':
scaleX -= 0.1;
scaleY -= 0.1;
scaleZ -= 0.1;
break;
case 'r':
angleX = 0.0;
angleY = 0.0;
angleZ = 0.0;
translateX = 0.0;
translateY = 0.0;
translateZ = 0.0;
scaleX = 1.0;
scaleY = 1.0;
scaleZ = 1.0;
break;
case 27: // ESC key
exit(0);
break;
}
glutPostRedisplay();
}
// Initialization function
void init() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
// Reshape function
void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (float)w / h, 1, 100);
glMatrixMode(GL_MODELVIEW);
}
// Main function
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("3D Geometric Operations");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
init();
glutMainLoop();
return 0;
}
*********************************************************************************************
Program 4:2D Transformations
#include <GL/glut.h>
#include <math.h>
GLfloat vertices[][2] = {
{0.0, 0.5},
{-0.5, -0.5},
{0.5, -0.5}
};
GLfloat angle = 0.0;
GLfloat translateX = 0.0;
GLfloat translateY = 0.0;
GLfloat scaleX = 1.0;
GLfloat scaleY = 1.0;
void display();
void menu(int option);
void createMenu();
void display() {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(translateX, translateY, 0);
glRotatef(angle, 0, 0, 1);
glScalef(scaleX, scaleY, 1);
glColor3f(1, 1, 1);
glBegin(GL_TRIANGLES);
for (int i = 0; i < 3; i++) {
glVertex2fv(vertices[i]);
}
glEnd();
glFlush();
}
void menu(int option) {
switch (option) {
case 1:
translateX -= 0.1;
break;
case 2:
translateX += 0.1;
break;
case 3:
translateY -= 0.1;
break;
case 4:
translateY += 0.1;
break;
case 5:
scaleX += 0.1;
scaleY += 0.1;
break;
case 6:
scaleX -= 0.1;
scaleY -= 0.1;
break;
case 7:
angle += 10.0;
if (angle > 360) angle -= 360;
break;
case 8:
angle -= 10.0;
if (angle < 0) angle += 360;
break;
case 9:
angle = 0.0;
translateX = 0.0;
translateY = 0.0;
scaleX = 1.0;
scaleY = 1.0;
break;
case 10:
exit(0);
break;
}
glutPostRedisplay();
}
void createMenu() {
int menuID = glutCreateMenu(menu);
glutAddMenuEntry("Translate left", 1);
glutAddMenuEntry("Translate right", 2);
glutAddMenuEntry("Translate down", 3);
glutAddMenuEntry("Translate up", 4);
glutAddMenuEntry("Scale up", 5);
glutAddMenuEntry("Scale down", 6);
glutAddMenuEntry("Rotate clockwise", 7);
glutAddMenuEntry("Rotate anticlockwise", 8);
glutAddMenuEntry("Reset", 9);
glutAddMenuEntry("Exit", 10);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
void init() {
glClearColor(0, 0, 0, 1);
}
void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(800, 600);
glutCreateWindow("2D Transformation");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
createMenu();
init();
glutMainLoop();
return 0;
}
*********************************************************************************************
Program 5:3D Transformations
#include <stdlib.h>
#include <GL/glut.h>
// Define cube vertices
GLfloat vertices[][3] = {
{-1, -1, -1},
{1, -1, -1},
{1, 1, -1},
{-1, 1, -1},
{-1, -1, 1},
{1, -1, 1},
{1, 1, 1},
{-1, 1, 1}
};
// Define cube edges
GLint edges[][2] = {
{0, 1},
{1, 2},
{2, 3},
{3, 0},
{4, 5},
{5, 6},
{6, 7},
{7, 4},
{0, 4},
{1, 5},
{2, 6},
{3, 7}
};
// Define rotation angles
GLfloat angleX = 0.0;
GLfloat angleY = 0.0;
GLfloat angleZ = 0.0;
// Define translation offsets
GLfloat translateX = 0.0;
GLfloat translateY = 0.0;
GLfloat translateZ = 0.0;
// Define scaling factors
GLfloat scaleX = 1.0;
GLfloat scaleY = 1.0;
GLfloat scaleZ = 1.0;
// Display function
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Set up perspective projection
gluLookAt(3, 3, 3, 0, 0, 0, 0, 1, 0);
// Apply transformations
glTranslatef(translateX, translateY, translateZ);
glRotatef(angleX, 1, 0, 0);
glRotatef(angleY, 0, 1, 0);
glRotatef(angleZ, 0, 0, 1);
glScalef(scaleX, scaleY, scaleZ);
// Draw cube
glColor3f(1, 1, 1);
glBegin(GL_LINES);
for (int i = 0; i < 12; i++) {
glVertex3fv(vertices[edges[i][0]]);
glVertex3fv(vertices[edges[i][1]]);
}
glEnd();
glutSwapBuffers();
}
// Keyboard function for scaling and translation
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case 'w':
translateY += 0.1;
break;
case 's':
translateY -= 0.1;
break;
case 'a':
translateX -= 0.1;
break;
case 'd':
translateX += 0.1;
break;
case 'q':
translateZ += 0.1;
break;
case 'e':
translateZ -= 0.1;
break;
case 'X':
angleX += 5.0f;
break;
case 'x':
angleX -= 5.0f;
break;
case 'Y':
angleY += 5.0f;
break;
case 'y':
angleY -= 5.0f;
break;
case 'Z':
angleZ += 5.0f;
break;
case 'z':
angleZ -= 5.0f;
break;
case '+':
scaleX += 0.1;
scaleY += 0.1;
scaleZ += 0.1;
break;
case '-':
scaleX -= 0.1;
scaleY -= 0.1;
scaleZ -= 0.1;
break;
case 'r':
angleX = 0.0;
angleY = 0.0;
angleZ = 0.0;
translateX = 0.0;
translateY = 0.0;
translateZ = 0.0;
scaleX = 1.0;
scaleY = 1.0;
scaleZ = 1.0;
break;
case 27: // ESC key
exit(0);
break;
}
glutPostRedisplay();
}
// Initialization function
void init() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
// Reshape function
void reshape(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (float)w / h, 1, 100);
glMatrixMode(GL_MODELVIEW);
}
// Main function
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("3D Transformations");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
init();
glutMainLoop();
return 0;
}
*********************************************************************************************
Program 6:Animation
#include <GL/glut.h>
#include <math.h>
int windowWidth = 800;
int windowHeight = 600;
int squareSize = 50;
int squarePosX = 0;
float animationSpeed = 1.0;
void init() {
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0, windowWidth, 0.0, windowHeight);
}
void drawSquare() {
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_QUADS);
glVertex2i(squarePosX, windowHeight / 2);
glVertex2i(squarePosX + squareSize, windowHeight / 2);
glVertex2i(squarePosX + squareSize, windowHeight / 2 + squareSize);
glVertex2i(squarePosX, windowHeight / 2 + squareSize);
glEnd();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
drawSquare();
glutSwapBuffers();
}
void update(int value) {
// Move the square to the right
squarePosX += animationSpeed;
// If the square moves out of the screen, reset its position
if (squarePosX > windowWidth) {
squarePosX = -squareSize; // Start from the left edge again
}
// Varying animation speed
animationSpeed += 0.01; // Increase animation speed linearly
glutPostRedisplay(); // Update the display
glutTimerFunc(1000 / 60, update, 0); // 60 frames per second
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(windowWidth, windowHeight);
glutInitWindowPosition(100, 100);
glutCreateWindow("Animation Effects with Varying Speed");
init();
glutDisplayFunc(display);
glutTimerFunc(0, update, 0);
glutMainLoop();
return 0;
}
*********************************************************************************************
Program 7:Image Quadrants
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Convert the image from BGR to RGB
img = cv2.cvtColor(cv2.imread('sample.jpg'), cv2.COLOR_BGR2RGB)
# Get the height and width of the image
height, width = img.shape[:2]
# Split the image into four quadrants
quad1 = img[:height//2, :width//2]
quad2 = img[:height//2, width//2:]
quad3 = img[height//2:, :width//2]
quad4 = img[height//2:, width//2:]
# Display the quadrants in a single figure
plt.figure(figsize=(10, 10))
plt.subplot(2, 2, 1)
plt.imshow(quad1)
plt.title("Quadrant 1")
plt.axis("off")
plt.subplot(2, 2, 2)
plt.imshow(quad2)
plt.title("Quadrant 2")
plt.axis("off")
plt.subplot(2, 2, 3)
plt.imshow(quad3)
plt.title("Quadrant 3")
plt.axis("off")
plt.subplot(2, 2, 4)
plt.imshow(quad4)
plt.title("Quadrant 4")
plt.axis("off")
plt.show()
****************************************************************************************
Program 8:Transform, Scale and Rotate
import cv2
import numpy as np
# Load the image
image_path = "sample.jpg" # Replace with the path to your image
img = cv2.imread(image_path)
# Get the image dimensions
height, width = img.shape[:2]
# Define the transformation matrices
rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), 45, 1) # Rotate by 45 degrees
scaling_matrix = cv2.getRotationMatrix2D((0, 0), 0, 1.5) # 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 + 100, height + 50))
# 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()
*************************************************************************************************************************
Program 9:Edges, Textures and Filters
import cv2
import numpy as np
# Load the image
image_path = "sample.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()
************************************************************************************************************************
Program 10:Blur and Smoothing
import numpy as np
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("sample.jpg",cv2.IMREAD_GRAYSCALE)
image_array = np.array(img)
print(image_array)
def sharpen():
return np.array([[1,1,1],[1,1,1],[1,1,1]])
def filtering(image, kernel):
m, n = kernel.shape
if (m == n):
y, x = image.shape
y = y - m + 1 # shape of image - shape of kernel + 1
x = x - m + 1
new_image = np.zeros((y,x))
for i in range(y):
for j in range(x):
new_image[i][j] = np.sum(image[i:i+m, j:j+m]*kernel)
return new_image
# Display the original and sharpened images
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image_array,cmap='gray')
plt.title("Original Grayscale Image")
plt.axis("off")
plt.subplot(1, 2, 2)
plt.imshow(filtering(image_array, sharpen()),cmap='gray')
plt.title("Blurred Image")
plt.axis("off")
plt.show()
*****************************************************************************************************************
Program 11:Contour
import cv2
import numpy as np
# Load the image
image_path = 'sample.jpg'
image = cv2.imread(image_path)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply thresholding to create a binary image
_, binary_image = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Draw all contours on the original image
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)
# Display the binary image and the result
cv2.imshow('Contours', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
******************************************************************************************************************************
Program 12:Detect Face
import cv2
# Load the pre-trained Haar Cascade classifier for face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# Read the input image (replace 'your_image.jpg' with the actual image path)
image_path = 'faces.jpg'
image = cv2.imread(image_path)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=2)
# Draw rectangles around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
# Save or display the result
cv2.imwrite('detected_faces.jpg', image) # Save the result
cv2.imshow('Detected Faces', image) # Display the result
cv2.waitKey(0)
cv2.destroyAllWindows()