0% found this document useful (0 votes)
6 views41 pages

CVLab

The document outlines a series of programming exercises focused on image processing using Python and OpenCV, including tasks such as loading, manipulating, and filtering images. Each exercise includes an aim, algorithm, and code implementation, covering topics like image addition, resizing, rotation, and binarization. The document serves as a practical guide for learning image processing techniques through hands-on programming.

Uploaded by

HACKER HASSAN
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)
6 views41 pages

CVLab

The document outlines a series of programming exercises focused on image processing using Python and OpenCV, including tasks such as loading, manipulating, and filtering images. Each exercise includes an aim, algorithm, and code implementation, covering topics like image addition, resizing, rotation, and binarization. The document serves as a practical guide for learning image processing techniques through hands-on programming.

Uploaded by

HACKER HASSAN
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

S.

Date Programs Page Satff


No No Sign

1 31/01/24 Image Loading, Exploring, and Displaying 2


an Image

2 22/01/24 Access and Manipulte of Image Pixels 5

Images Transformations
3 14/02/24 i) Resizing 8
ii) Rotation

4 26/02/24 Addition operation of Two Images 12

Image Filtering operations


5 02/03/24 i) Mean Filtering 16
ii) Gaussian Filtering

6 03/03/24 Image Binarization Using Simple 20


Thresholding method

7 07/03/24 Edge Desicion operation using Sobel and 24


Scharr Gradients

8 08/03/24 Find Grayscale and RGB Histograms of an 29


Image

9 12/03/24 Segment an Image using K-means 32


Clustering algorithm

10 13/03/24 To classify an image using KNN 37


Classification

1
Ex no:1 Image Loading, Exploring, and Displaying an Image

Date:31-01-24

Aim: To write a program Image Loading, Exploring, and Displaying an Image


using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is


used for computer vision tasks like image processing.
 import images as images: This line attempts to import a
module named images. However, it’s unclear what this module
does because there’s no standard library named images in
Python. It’s possible that this module is custom-defined in the
larger program that this code snippet comes from.

2. Read the image:

 image_cv2 = [Link](r'C:\Users\ELCOT\Desktop\magical
[Link]'): This line reads an image from the specified path using
the [Link]() function. The r before the path string is used
to specify a raw string, which is necessary to avoid interpreting
backslashes within the path as escape sequences.

3. Display the image:

 [Link]('Nature image using Desktop', image_cv2): This line


displays the loaded image in a window titled "Nature image
using Desktop" using the [Link]() function.

4. Wait for a key press:

 [Link](0): This line pauses the program execution and


waits for the user to press a key. The 0 argument in
[Link]() indicates that the program should wait
indefinitely for a key press.

2
5. Close all windows:

 [Link](): This line closes all the windows


created by OpenCV, including the window that was displaying
the image.

Code

import cv2

image_cv2= [Link](r'C:\Users\ELCOT\Desktop\magical [Link]')

[Link]("nature image using Desktop", image_cv2)

[Link](0)

[Link]()

3
Output:

Result:

This program has been executed successfully.

4
Ex no: 2 Access and Manipulate of Image Pixels

Date:22-01-24

Aim:To write a program Access and Manipulte of Image Pixels using python.

Algorithm:

1. Import libraries:

 Import the OpenCV library (cv2) for image processing tasks.


 Import the NumPy library (numpy) for numerical operations on
arrays (likely used for image manipulation in this program).

2. Read the image:

 Use [Link]() to read the image from a specified path. The


path to the image file needs to be provided within the quotation
marks.

3. Modify the image (Optional):

 The provided code snippet doesn't explicitly modify the image.


However, image processing libraries like OpenCV offer various
functions to manipulate images. You can explore these
functions for various purposes like filtering noise, adjusting
colors, or detecting objects in the image.

4. Display the image:

 Use [Link]() to display the image in a window with a


specified title.

5. Wait for a key press:

 Use [Link](0) to pause the program and wait for the user
to press a key.

6. Close all windows:

 Use [Link]() to close all windows created by


OpenCV.

5
7. Save the modified image (Optional):

 Use [Link]() to save the modified image to a specified file


path, if any modifications were made to the image.

Code

import cv2

import numpy as np

image = [Link]("path/to/your/[Link]")

blue_value = image[100, 50, 0]

print(f"Blue value at (100, 50): {blue_value}")

image[200, 100] = [0, 255, 0]

image[70:120, 50:150] = [0, 0, 255]

[Link]("Modified Image", image)

[Link](0)

[Link]()

[Link]("modified_image.jpg", image)

6
Result:

This program has been executed successfully.

7
Ex no: 3 Images Transformations Resizing and Rotation

Date:14-02-24

Aim: To write a program Images Transformations Resizing and Rotation


using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing.
 import numpy as np: This line imports the NumPy library,
which is used for numerical operations on arrays (often used for
image manipulation).

2. Read the image:

 img = [Link](r"D:\Pictures\pexels-philippedonn-
[Link].1"): This line reads an image from the specified
path using the [Link]() function. The r before the path
string is used to specify a raw string, which is necessary to
avoid interpreting backslashes within the path as escape
sequences.

3. Resize the image:

 height, width = [Link][:2]: This line gets the height and


width of the image from the shape attribute of the image
object.
 res = [Link](img, (int(width/2), int(height/2)),
interpolation=cv2.INTER_AREA): This line resizes the image to
half its original size using the [Link]() function. The
interpolation method used here is cv2.INTER_AREA, which is
suitable for resizing images down.

4. Display the image:

8
 [Link]('image', res): This line displays the resized image in a
window titled "image" using the [Link]() function.

5. Wait for a key press:

 [Link](0): This line pauses the program execution and


waits for the user to press a key. The 0 argument in
[Link]() indicates that the program should wait indefinitely
for a key press.

6. Close all windows:

 [Link](): This line closes all the windows created


by OpenCV, including the window that was displaying the image.

Code

Resize:

import numpy as np

import cv2

img = [Link](r'D:\Pictures\[Link]',1)

height, width = [Link][:2]

res = [Link](img,(int(width/2), int(height/2)), interpolation =


cv2.INTER_AREA)

[Link]('image', res)

[Link](0)

[Link]()

9
Output(Resize):

Rotate:

import numpy as np

import cv2

img = [Link](r'D:\Pictures
Pictures\[Link]',1)

h, w = [Link][:2]

center = (w/2, h/2)

mat = cv2.getRotationMatrix2D(center, 90, 1)

rotimg = [Link](img, mat, (h, w))

[Link]('original', img)

[Link]('rotated', rotimg)

[Link](0)

[Link]()

10
Output(Rotate):

Result:

This program has been executed


xecuted successfully.

11
Ex no: 4 Addition operations of Two Images

Date:26-02-24

Aim:To write a program Addition operations of Two Images using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing.

2. Define functions:

 add_images(image1_path, image2_path, output_path): This


function takes three arguments: the paths to the two images to
be added and the path to save the resulting image.

3. Read the images:

 image1 = [Link](image1_path): This line reads the first


image from the specified path using the [Link]() function.
 image2 = [Link](image2_path): This line reads the second
image from the specified path using the [Link]() function.

4. Check image dimensions:

 if [Link] != [Link]: This line checks if the two


images have the same dimensions (height and width).
 If the dimensions are not the same, the function prints an error
message and exits.

5. Add the images:

 added_image = [Link](image1, image2): This line adds the two


images together pixel-wise using the [Link]() function.

6. Display the added image:

12
 [Link]("Added Image", added_image): This line displays the
added image in a window titled "Added Image" using the
[Link]() function.

7. Save the added image:

 [Link](output_path, added_image): This line saves the


added image to the specified path using the [Link]()
function.

8. Call the function:

 add_images("path/to/[Link]", "path/to/[Link]",
"added_image.jpg"): This line calls the add_images() function
with the paths to the two images and the desired output path.

Code

import cv2

def add_images(image1_path, image2_path, output_path):

"""

Adds two images and saves the result.

Args:

image1_path: Path to the first image file.

image2_path: Path to the second image file.

output_path: Path to save the resulting image.

"""

image1 = [Link](image1_path)

image2 = [Link](image2_path)

if [Link] != [Link]:

print("Error: Images must have the same dimensions.")

return

13
added_image = [Link](image1, image2)

[Link]("Added Image", added_image)

[Link](0)

[Link](output_path, added_image)

image1_path = "path/to/[Link]"

image2_path = "path/to/[Link]"

output_path = "added_image.jpg"

add_images(image1_path, image2_path, output_path)

print("Image addition completed.")

Output:

14
Result:

This program has been executed successfully.

15
Ex no: 5 Image Filtering operations Mean and Gaussian Filtering

Date:02-03-24

Aim: To write a program Image Filtering operations Mean and Gaussian


Filtering using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing.
 import numpy as np: This line imports the NumPy library,
which is commonly used for numerical operations on arrays
(often used for image manipulation in OpenCV).

2. Read the image:

 image = [Link]("path/to/your/[Link]"): This line reads


an image from the specified path using the [Link]()
function.

3. Define kernel sizes:

 kernel_size_mean = 3: This line defines the kernel size for mean


filtering. The kernel size determines the area around a pixel that
is used to calculate the average intensity for filtering.
 kernel_size_gauss = 5: This line defines the kernel size for
Gaussian filtering. Gaussian filters use a bell-shaped curve to
weight the pixels within the kernel, giving more importance to
pixels closer to the center.

4. Apply mean filtering:

 filtered_mean = [Link]([Link](), (kernel_size_mean,


kernel_size_mean)): This line applies a mean filter to the image
using the [Link]() function. The .copy() method is used to
create a copy of the image to avoid modifying the original image.

16
5. Apply Gaussian filtering:

 filtered_gauss = [Link]([Link](),
(kernel_size_gauss, kernel_size_gauss), 0): This line applies a
Gaussian filter to the image using the [Link]()
function.

6. Display the original and filtered images:

 [Link]('Original Image', image): This line displays the


original image in a window titled "Original Image" using the
[Link]() function.
 [Link]("Mean Filtered", filtered_mean): This line displays
the mean-filtered image in a window titled "Mean Filtered" using
the [Link]() function.
 [Link]("Gaussian Filtered", filtered_gauss): This line
displays the Gaussian-filtered image in a window titled
"Gaussian Filtered" using the [Link]() function.

7. Wait for a key press:

 [Link](0): This line pauses the program execution and


waits for the user to press a key. The 0 argument in
[Link]() indicates that the program should wait indefinitely
for a key press.

[Link] all windows:

 [Link](): This line closes all the windows


created by OpenCV, including the windows that were displaying
the images.

9. Save the filtered images (Optional):

 The code snippet doesn't include saving the filtered images. You
can use [Link]() to save the filtered images if needed.

Code

import cv2

import numpy as np

image = [Link]("path/to/your/[Link]")

17
kernel_size_mean = 3

kernel_size_gauss = 5

filtered_mean = [Link]([Link](), (kernel_size_mean, kernel_size_mean))

filtered_gauss = [Link]([Link](), (kernel_size_gauss,


kernel_size_gauss), 0)

[Link]("Original Image", ima


image)

[Link]("Mean Filtered", filtered_mean)

[Link]("Gaussian Filtered", filtered_gauss)

[Link](0)

[Link]()

[Link]("mean_filtered_image.jpg", filtered_mean)

[Link]("gaussian_filtered_image.jpg", filtered_gauss)

print("Mean
an and Gaussian filtering completed.")

Output:

18
Result:

This program has been executed successfully.

19
Ex no: 6 Image Binarization Using Simple Thresholding method

Date:03-03-24

Aim: To write a program Image Binarization UsingSimple Thresholding method


using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library for computer
vision tasks.
 import numpy as np: This line imports the NumPy library for
numerical operations on arrays (often used for image
manipulation in OpenCV).

2. Read the image:

 image = [Link]('path/to/your/grayscale_image.jpg',
cv2.IMREAD_GRAYSCALE): This line reads a grayscale image
from the specified path using [Link](). The
cv2.IMREAD_GRAYSCALE flag ensures the image is loaded in
grayscale mode.

3. Set threshold value:

 threshold = 127: This line defines the threshold value for


binarization. Pixels with intensity values greater than or equal to
the threshold will be set to white (1), and pixels with intensity
values less than the threshold will be set to black (0).

4. Apply thresholding:

 ret, thresholded_image = [Link](image, threshold, 255,


cv2.THRESH_BINARY): This line applies thresholding to the
grayscale image using [Link]().
 The first argument is the grayscale image.
 The second argument is the threshold value.

20
 The third argument is the maximum value to be used with the
threshold (usually set to 255 for 8-bit images).
 The fourth argument is the thresholding method, which is set to
cv2.THRESH_BINARY for basic binary thresholding.
 The function outputs a return value (ret) and the thresholded
binary image.

5. Display the original and thresholded images:

 [Link]('Original Grayscale Image', image): This line displays


the original grayscale image in a window titled "Original
Grayscale Image" using [Link]().
 [Link]('Thresholded Binary Image', thresholded_image):
This line displays the thresholded binary image in a window
titled "Thresholded Binary Image" using [Link]().

6. Wait for a key press:

 [Link](0): This line pauses the program execution and waits


for the user to press a key. The 0 argument in [Link]()
indicates that the program should wait indefinitely for a key
press.

7. Close all windows:

 [Link](): This line closes all the windows created


by OpenCV, including the windows that were displaying the
images.

8. Save the thresholded image (Optional):

 The code snippet doesn't include saving the thresholded image.


You can use [Link]() to save the thresholded image if
needed.

Code

import cv2

import numpy as np

21
image = [Link]("path/to/your/grayscale_image.jpg",
cv2.IMREAD_GRAYSCALE)

threshold = 127

ret, thresholded_image = [Link](image, th


threshold, 255,
cv2.THRESH_BINARY)

[Link]("Original Grayscale Image", image)

[Link]("Thresholded Binary Image", thresholded_image)

[Link](0)

[Link]()

[Link]("thresholded_image.jpg", thresholded_image)

print("Image binari zation


on using simple thresholding completed.")

22
Result:

This program has been executed successfully.

23
Ex no: 7 Edge Detection operation using Sobel and Scharr Gradients

Date:07-03-24

Aim: To write a program Edge Detection operation using Sobel and Scharr
Gradients using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing.
 import numpy as np: This line imports the NumPy library, which
is commonly used for numerical operations on arrays (often used
for image manipulation in OpenCV).

2. Define functions:

 edge_detection(image, method="Sobel"): This function takes an


image as input and an optional argument for the edge detection
method (Sobel or Scharr). By default, the method is set to
"Sobel".

3. Read the image:

 image = [Link]('path/to/your/[Link]'): This line reads an


image from the specified path using the [Link]() function.

4. Convert to grayscale (if needed):

 gray_image = [Link](image, cv2.COLOR_BGR2GRAY): This


line converts the image to grayscale if it's a color image. Edge
detection algorithms typically work better on grayscale images.

5. Apply threshold (optional):

 The code snippet doesn't explicitly apply thresholding to the


edge-detected image. Thresholding can be used to convert the
edge magnitude image to a binary image (where pixels above a

24
certain threshold are considered edges and pixels below are set to
black).

6. Display the original and edge-detected images:

 [Link]('Original Image', image): This line displays the


original image in a window titled "Original Image" using the
[Link]() function.
 [Link]('Edge-detected Image (Magnitude)', magnitude): This
line displays the magnitude image from the edge detection in a
window titled "Edge-detected Image (Magnitude)" using the
[Link]() function.

7. Wait for a key press:

 [Link](0): This line pauses the program execution and waits


for the user to press a key. The 0 argument in [Link]()
indicates that the program should wait indefinitely for a key
press.

8. Close all windows:

 [Link](): This line closes all the windows created


by OpenCV, including the windows that were displaying the
images.

Code

import cv2

import numpy as np

def edge_detection(image, method="Sobel"):

"""

Detects edges in an image using the specified method.

Args:

image: The input image (grayscale recommended).

method: Edge detection method ("Sobel" or "Scharr").

25
Returns:

The image with detected edges.

"""

if len([Link]) > 2:

image = [Link](image, cv2.COLOR_BGR2GRAY)

if method == "Sobel":

sobelx = [Link](image, cv2.CV_64F, 1, 0, ksize=3)

sobely = [Link](image, cv2.CV_64F, 0, 1, ksize=3)

magnitude, _ = [Link](sobelx, sobely, angleInDegrees=True)

elif method == "Scharr":

sobelx = [Link](image, cv2.CV_64F, 1, 0)

sobely = [Link](image, cv2.CV_64F, 0, 1)

magnitude, _ = [Link](sobelx, sobely, angleInDegrees=True)

else:

print(f"Invalid method: {method}. Supported methods are 'Sobel' and


'Scharr'.")

return None

magnitude = [Link](magnitude)

magnitude = np.uint8(255 * magnitude / [Link](magnitude))

return magnitude

image = [Link]("path/to/your/[Link]")

sobel_edges = edge_detection([Link]())

scharr_edges = edge_detection([Link](), method="Scharr")

[Link]("Original Image", image)

[Link]("Sobel Edges", sobel_edges)

26
[Link]("Scharr
[Link]("Scharr Edges", scharr_edges)

[Link](0)

[Link]()

print("Edge detection using Sobel and Scharr gradients completed.")

27
Result:

This program has been executed successfully.

28
Ex no: 8 Find Grayscale and RGB Histograms of an Image

Date:08-03-24

Aim: To write a program Find Grayscale and RGB Histograms of an Image


using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing.

2. Read the image:

 image = [Link]('path/to/your/[Link]'): This line reads an


image from the specified path using the [Link]() function.

3. Convert to grayscale:

 gray_image = [Link](image, cv2.COLOR_BGR2GRAY): This


line converts the color image to grayscale using [Link]().
Adaptive thresholding typically works better on grayscale images.

4. Apply adaptive thresholding:

 thresh = [Link](gray_image, 255,


cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2):
This line applies adaptive thresholding to the grayscale image
using [Link]().
 The first argument is the grayscale image.
 The second argument is the maximum output value for the
thresholding.
 The third argument specifies the adaptive thresholding method,
which is set to cv2.ADAPTIVE_THRESH_MEAN_C for mean C
(average intensity in the neighborhood).
 The fourth argument is the type of thresholding, which is set to
cv2.THRESH_BINARY for binary thresholding.

29
 The fifth argument is the neighborhood size for calculating the
adaptive threshold.
 The sixth argument is the constant subtracted from the mean or
median (depending on the method) before applying the threshold.

5. Display the original and thresholded images:

 [Link]('Original Image', image): This line displays the


original color image in a window titled "Original Image" using
the [Link]() function.
 [Link]('Thresholded Image', thresh): This line displays the
thresholded binary image in a window titled "Thresholded
Image" using the [Link]() function.

6. Wait for a key press:

 [Link](0): This line pauses the program execution and waits


for the user to press a key. The 0 argument in [Link]()
indicates that the program should wait indefinitely for a key
press.

7. Close all windows:

 [Link](): This line closes all the windows created


by OpenCV, including the windows that were displaying the
images.

Code

import cv2

image = [Link](r'D:\Pictures\[Link]')

[Link](r'D:\Pictures\[Link]',image)

grayscale = [Link](image, cv2.COLOR_BGR2GRAY)

[Link]('Grayscale', grayscale)

30
Result:

This program has been executed successfully.

31
Ex no: 9 Segment an Image Using K-means Clustering algorithm

Date:12-03-24

Aim: To write a program Segment an Image Using K-means Clustering


algorithm using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing.
 import numpy as np: This line imports the NumPy library, which
is commonly used for numerical operations on arrays (often used
for image manipulation in OpenCV).

2. Define functions:

 kmeans_segmentation(image, k):: This function takes an image


and the desired number of clusters (k) as input and performs K-
Means segmentation.

3. Read the image:

 image = [Link](image_path): This line reads an image from


the specified path (image_path) using the [Link]() function.

4. Reshape the image:

 image_data = [Link](([Link][0] * [Link][1], 3)):


This line reshapes the image data into a 2D array where each row
represents a pixel and each column represents the Blue, Green,
and Red (BGR) color channels of the pixel.

5. Convert to float data type:

 image_data = np.float32(image_data): This line converts the image


data from an unsigned integer (uint8) to a single-precision
floating-point (float32) data type. K-Means clustering algorithms
often work better with floating-point data.

32
6. Define criteria:

 criteria = cv2.TERM_CRITERIA + cv2.TERM_EPS +


cv2.TERM_ITER, 10, 1.0: This line defines the termination criteria
for the K-Means algorithm using cv2.TERM_CRITERIA. Here, it
specifies that the algorithm will terminate either when the
maximum number of iterations (10) is reached or when the
epsilon value (minimum change in the center between iterations)
becomes less than 1.0.

7. Apply K-Means segmentation:

 ret, labels, centers = [Link](image_data, k, None, criteria,


10, cv2.KMEANS_RANDOM_CENTERS): This line performs K-
Means clustering on the image data using the [Link]()
function.
 The first argument is the reshaped image data.
 The second argument is the number of desired clusters (k).
 The third argument is set to None because we don't provide any
initial cluster centers.
 The fourth argument is the termination criteria defined earlier.
 The fifth argument specifies the maximum number of attempts
(10) to run the K-Means algorithm.
 The sixth argument specifies the K-Means initialization method,
which is set to cv2.KMEANS_RANDOM_CENTERS to choose
random cluster centers.
 The function outputs a return value (ret), cluster labels for each
pixel (labels), and the computed cluster centers (centers).

8. Reshape the labels:

 segmented_image = [Link]([Link][0],
[Link][1]): This line reshapes the cluster labels back into the
original image shape, where each pixel value now represents its
assigned cluster number.

9. Convert segmented image to color (optional):

 The code snippet doesn't explicitly convert the segmented image


(represented by cluster labels) into a color image. You can use
cluster centers and label information to assign a color to each
cluster and create a color-coded segmentation output.

33
10. Display the original and segmented images:

 [Link]("Original Image", image): This line displays the


original image in a window titled "Original Image" using the
[Link]() function.
 [Link]("Segmented Image", segmented_image): This line
displays the segmented image (cluster labels) in a window titled
"Segmented Image" using the [Link]() function.

11. Wait for a key press:

 [Link](0): This line pauses the program execution and waits


for the user to press a key. The 0 argument in [Link]()
indicates that the program should wait indefinitely for a key
press.

12. Close all windows:

 [Link](): This line closes all the windows created


by OpenCV, including the windows that were displaying the
images.

Code

import cv2

import numpy as np

def kmeans_segmentation(image, k):

"""

Segments an image using K-Means clustering.

Args:

image: The input image (converted to BGR format).

k: The number of clusters (desired number of segments).

Returns:

The segmented image.

34
"""

image_data = [Link](([Link][0] * [Link][1], 3))

image_data = np.float32(image_data)

criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10,


1.0)

ret, labels, centers = [Link](image_data, k, None, criteria, 10,


cv2.KMEANS_RANDOM_CENTERS)

segmented_image = centers[[Link]()].reshape([Link])

return segmented_image

image = [Link]("path/to/your/[Link]")

image = [Link](image, cv2.COLOR_RGB2BGR)

num_clusters = 4

segmented_image = kmeans_segmentation([Link](), num_clusters)

[Link]("Original Image", image)

[Link]("Segmented Image", segmented_image)

[Link](0)

[Link]()

print("Image segmentation using K-Means clustering completed.")

35
Result:

This program has been executed successfully.

36
Ex no: 10 To Classify an Image using KNN Classification algorithm

Date:13-03-24

Aim: To write a program To Classify an Image using KNN Classification


algorithm using python.

Algorithm:

1. Import libraries:

 import cv2: This line imports the OpenCV library, which is used
for computer vision tasks like image processing and classification.
 import numpy as np: This line imports the NumPy library, which
is commonly used for numerical operations on arrays (often used
for image manipulation in OpenCV).
 from [Link] import KNeighborsClassifier: This line
imports the KNeighborsClassifier class from scikit-learn, a
popular machine learning library in Python.

2. Load the pre-trained model:

 model = [Link].KNearest_create(): This line creates a K-Nearest


Neighbors (KNN) classification model using OpenCV's machine
learning module.
 [Link](<model_file_path>): This line loads a pre-trained KNN
classification model from a file. The specific file path needs to be
provided.

3. Prepare the image:

 image = [Link](<image_path>): This line reads an image from


the specified path (image_path) using the [Link]() function.
 preprocessor = SimplePreprocessor(<target_width>,
<target_height>): This line creates a simple preprocessor object to
resize the image to a specific width and height (depending on how
the model was trained).

37
 image = preprocessor.preprocess_image(image): This line
preprocesses the image using the created preprocessor object
(likely resizing).

4. Make predictions:

 prediction = [Link](<image_data>): This line uses the


loaded KNN model to predict the class label for the preprocessed
image data. The specific format of <image_data> might depend on
how the model was trained, but it's likely a NumPy array
representing the image.

5. Display the image and prediction:

 [Link]("Image", image): This line displays the image in a


window titled "Image" using the [Link]() function.
 print("Predicted class:", prediction[1][0]): This line prints the
predicted class label from the KNN model prediction.

6. Wait for a key press:

 [Link](0): This line pauses the program execution and waits


for the user to press a key. The 0 argument in [Link]()
indicates that the program should wait indefinitely for a key
press.

7. Close all windows:

 [Link](): This line closes all the windows created


by OpenCV, including the window that was displaying the image.

Code

import necessary packages

from [Link] import KNeighborsClassifier

from [Link] import LabelEncoder

from sklearn.model_selection import train_test_split

from [Link] import classification_report

38
from pyimagesearch import simplepreprocessor

from pyimagesearch import simpledatasetloader

from imutils import paths

import os

import glob

import cv2

import numpy as np

def getListOfFiles(dirName):

listOfFile = [Link](dirName)

allFiles = list()

for entry in listOfFile:

fullPath = [Link](dirName, entry)

if [Link](fullPath):

allFiles = allFiles + getListOfFiles(fullPath)

else:

[Link](fullPath)

return allFiles

imagePaths = getListOfFiles("./datasets/") ## Folder structure: datasets -->


sub-folders with labels name

data = []

lables = []

c = 0 ## to see the progress

for image in imagePaths:

lable = [Link]([Link](image)[0])[1]

[Link](lable)

39
img = [Link](image)

img = [Link](img, (32, 32), interpolation = cv2.INTER_AREA)

[Link](img)

c=c+1

print(c)

data = [Link](data)

lables = [Link](lables)

le = LabelEncoder()

lables = le.fit_transform(lables)

myset = set(lables)

print(myset)

dataset_size = [Link][0]

data = [Link](dataset_size,-1)

print([Link])

print([Link])

print(dataset_size)

(trainX, testX, trainY, testY ) = train_test_split(data, lables, test_size= 0.25,


random_state=42)

model = KNeighborsClassifier(n_neighbors=3, n_jobs=-1)

[Link](trainX, trainY)

print(classification_report(testY, [Link](testX),
target_names=le.classes_))

40
Output:

Result:

This program has been executed successfully.

41

You might also like