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

ALCANTARAuLaboratory-6-Image-Processing-Student_031006

Image Proccessing Activity
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

ALCANTARAuLaboratory-6-Image-Processing-Student_031006

Image Proccessing Activity
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Jeffrey R.

Samonte

BScPE 4-1

Laboratory Module No. 6 – Image

Processing To introduce basic image processing techniques using Python and OpenCV.

IDLE Python 3.9

pip install opencv-python

OpenCV (Open-Source Computer Vision Library), developed by Intel, is a widely-used open-


source toolset for computer vision and image processing tasks. Python's accessibility and
OpenCV's extensive features make them a formidable duo for tasks like image
manipulation, object detection, facial recognition, and more. This combination is favored in
fields such as robotics, medical image analysis, and augmented reality. Together, Python and
OpenCV provide a robust platform for developing advanced computer vision
applications.

a. Create a folder on preferred destination and upload selfie image with “.jpg” file
extension.
b. Create a “.py” file and save it on the same destination
of images. c. Import image using open OpenCV.
d. Display the image using OpenCV ‘imshow’
function. e. Save the displayed image as a
new file.

Code:
import
cv2

# Load the image file (replace "abi.jpg" with your file name)
image = cv2.imread("abi.jpg")

# Show the loaded image in a window


cv2.imshow("Image", image)

# Save the image with a different name


cv2.imwrite("new_selfie.jpg", image)

# Wait until a key is pressed and then close the display window
cv2.waitKey(0)
cv2.destroyAllWindows()
CODE DISCUSSION:
This Python code uses OpenCV to load, display, and save an image. To do this, it starts with
loading the image through the command cv2.imread("abi.jpg"), where the image file, (abi.jpg), is found
in the same folder from where the Python script has been invoked. Replace "abi.jpg" with the name of
the image that you want to use. The loaded image is then shown in a window with the title of "Image" by
cv2.imshow ("Image", image). That is where you can preview the image before saving. It saves a copy of
the image as "new_selfie.jpg" using cv2.imwrite ("new_selfie.jpg", image). Thus, creating a new image
copy and giving it another name but keeping the previous image safe. After showing the picture, the
script waits until a key is pressed (cv2.waitKey(0)) and then, after detecting a pressed key, closes a
window with cv2.destroyAllWindows(). It's such an easy flow to load your image, see it, and save a new
version using just a few lines of code.

a. Adjust brightness and


contrast. Figure 1:
Original
Image
Figure 2: Brightness = 50, Contrast =
1.5 Figure 3: Brightness = 100,
Contrast = 1.5 Figure 4. Brightness =
200, Contrast = 1.5

Code:
import cv2
import numpy as np

# Load the image


image = cv2.imread("apekz.jpg") # Replace 'selfie.jpg' with your image filename

# Function to adjust brightness and contrast


def adjust_brightness_contrast(image, brightness=0, contrast=1.0):
return cv2.convertScaleAbs(image, alpha=contrast,
beta=brightness)
# Apply brightness and contrast
adjustments original = image # Figure 1:
Original Image
bright_50_contrast_1_5 = adjust_brightness_contrast(image, brightness=50, contrast=1.5) # Figure
2 bright_100_contrast_1_5 = adjust_brightness_contrast(image, brightness=100, contrast=1.5) #
Figure 3
bright_200_contrast_1_5 = adjust_brightness_contrast(image, brightness=200, contrast=1.5) #
Figure 4

# Save the results


cv2.imwrite("figure_1_original.jpg",
original)
cv2.imwrite("figure_2_brightness_50_contrast_1.5.jpg", bright_50_contrast_1_5)
cv2.imwrite("figure_3_brightness_100_contrast_1.5.jpg",
bright_100_contrast_1_5)
cv2.imwrite("figure_4_brightness_200_contrast_1.5.jpg",
bright_200_contrast_1_5)

# Display the results


cv2.imshow("Figure 1: Original Image", original)
cv2.imshow("Figure 2: Brightness 50, Contrast 1.5", bright_50_contrast_1_5)
cv2.imshow("Figure 3: Brightness 100, Contrast 1.5",
bright_100_contrast_1_5) cv2.imshow("Figure 4: Brightness 200, Contrast
1.5", bright_200_contrast_1_5)

# Wait and close all windows


cv2.waitKey(0)
cv2.destroyAllWindows()

CODE DISCUSSION:

The first code changes the brightness and contrast of an image. The function
cv2.convertScaleAbs scales the pixel values of the input image to enhance contrast by setting alpha
and brightness by beta. There are three output versions of the original image with their brightness
increased by 50, then 100, and lastly by 200 with a contrast factor of 1.5. These adjustments make
the image appear progressively brighter while maintaining contrast enhanced. The results are
displayed using OpenCV's imshow and saved as separate image files for reference.

b. Apply color
filters.
Figure 1: Original
Image
Figure 2: Sobel Filtered Image
Figure 3: Gaussian Filtered Ima
ge Figure 4:
Laplacian Filtered Image
Code:
import cv2
import numpy as np

# Load the image


image = cv2.imread("abi.jpg") # Replace 'selfie.jpg' with your image filename

# Sobel Filter
sobel = cv2.Sobel(image, cv2.CV_64F, 1, 1, ksize=3)

# Gaussian Filter
gaussian = cv2.GaussianBlur(image, (5, 5), 0)

# Laplacian Filter
laplacian = cv2.Laplacian(image, cv2.CV_64F)

# Convert results to uint8 for saving/displaying


sobel_uint8 = cv2.convertScaleAbs(sobel)
laplacian_uint8 = cv2.convertScaleAbs(laplacian)

# Save the results


cv2.imwrite("figure_1_original.jpg", image)
cv2.imwrite("figure_2_sobel_filtered.jpg", sobel_uint8)
cv2.imwrite("figure_3_gaussian_filtered.jpg", gaussian)
cv2.imwrite("figure_4_laplacian_filtered.jpg", laplacian_uint8)

# Display the results


cv2.imshow("Figure 1: Original Image", image) cv2.imshow("Figure 2:
Sobel Filtered Image", sobel_uint8) cv2.imshow("Figure 3: Gaussian
Filtered Image", gaussian) cv2.imshow("Figure 4: Laplacian Filtered
Image", laplacian_uint8)

# Wait and close all windows


cv2.waitKey(0)
cv2.destroyAllWindows()

CODE DISCUSSION:
The second code demonstrates three types of image filters: Sobel, Gaussian, and Laplacian,
showing how they each affect an image. The Sobel filter is applied with cv2.Sobel, which calculates
changes in pixel intensity both horizontally and vertically, making it good for detecting edges and
boundaries. The Gaussian filter is applied using cv2.GaussianBlur, which smooths the image by
averaging pixel values based on a Gaussian distribution, helping reduce noise and fine details. The
Laplacian filter is applied with cv2.Laplacian to calculate the second derivative of pixel intensity,
highlighting rapid intensity changes, like edges. The results from each filter are converted into an 8-
bit format for easy display and saving. Each filtered image is saved and shown in separate windows
so you can compare how each filter changes the image. This code is a practical way to demonstrate
techniques like edge detection, noise reduction, and feature enhancement

.
a. Filter image using convolution and
kernels b. Use 2x2, 5x5, and 10x10 kernel.

Code:
import cv2
import numpy as np

# Load the image


image = cv2.imread("abi.jpg") # Replace 'selfie.jpg' with your image filename

# Function to apply convolution using a kernel


def apply_convolution(image, kernel_size):
# Create a normalized kernel (all values add up to 1)
kernel = np.ones((kernel_size, kernel_size), np.float32) / (kernel_size ** 2)
return cv2.filter2D(image, -1, kernel)

# Apply kernels of sizes 2x2, 5x5, and 10x10


conv_2x2 = apply_convolution(image, 2)
conv_5x5 = apply_convolution(image, 5)
conv_10x10 = apply_convolution(image, 10)

# Save the results


cv2.imwrite("figure_1_original.jpg", image)
cv2.imwrite("figure_2_convolution_2x2.jpg", conv_2x2)
cv2.imwrite("figure_3_convolution_5x5.jpg", conv_5x5)
cv2.imwrite("figure_4_convolution_10x10.jpg", conv_10x10)
# Display the results
cv2.imshow("Figure 1: Original Image", image)
cv2.imshow("Figure 2: 2x2 Kernel", conv_2x2)
cv2.imshow("Figure 3: 5x5 Kernel", conv_5x5)
cv2.imshow("Figure 4: 10x10 Kernel", conv_10x10)

# Wait and close all windows


cv2.waitKey(0)
cv2.destroyAllWindows()

CODE DISCUSSION:
This code applies convolution to an image using normalized kernels of sizes 2x2, 5x5, and 10x10.
Convolution blurs the image by averaging the pixel values within the area covered by the kernel.
Smaller kernels (like 2x2) produce a gentle blur, while larger kernels (like 10x10) create a stronger
smoothing effect. The convolution is performed using the cv2.filter2D function. The resulting blurred
images are then saved and displayed, allowing you to see the varying degrees of smoothing based on
the different kernel sizes.

a. Capture an object with plain white background and named


as input_image.jpg b. Change the background of the object into yellow,
blue, and red.

Code:
import cv2
import numpy as np

# Load the image


image = cv2.imread("apekz.jpg") # Replace 'input_image.jpg' with your image filename
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Create a binary mask for the object (white background is treated as background)
_, mask = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY_INV)

# Function to change the background color


def change_background(image, mask, color):
# Create a solid background with the desired color
background = np.full_like(image, color, dtype=np.uint8)
# Combine the object and new background
return cv2.bitwise_or(background, background, mask=cv2.bitwise_not(mask)) +
cv2.bitwise_and(image, image, mask=mask)

# Change background to yellow, blue, and red


yellow_background = change_background(image, mask, (0, 255, 255)) # Yellow
blue_background = change_background(image, mask, (255, 0, 0)) # Blue
red_background = change_background(image, mask, (0, 0, 255)) # Red

# Save the results


cv2.imwrite("figure_1_yellow_background.jpg", yellow_background)
cv2.imwrite("figure_2_blue_background.jpg", blue_background)
cv2.imwrite("figure_3_red_background.jpg", red_background)

# Display the results


cv2.imshow("Figure 1: Yellow Background", yellow_background)
cv2.imshow("Figure 2: Blue Background", blue_background)
cv2.imshow("Figure 3: Red Background", red_background)

# Wait and close all windows


cv2.waitKey(0)
cv2.destroyAllWindows()

CODE DISCUSSION:
This code replaces the white background of an image with different solid colors like yellow, blue, and
red. First, the image is converted to grayscale to easily identify the white background. A binary mask
is created using cv2.threshold, where the white areas are identified as the background and the other
areas as the object. Solid color backgrounds are generated using NumPy arrays, and the object is
combined with the new background using bitwise operations (cv2.bitwise_or and cv2.bitwise_and).
The result is an image where the original background is replaced with bold colors, which is then
saved and displayed in OpenCV windows for reference.

Conclusion
The document, Laboratory Module No. 6 – Image Processing, introduces basic image processing
techniques using Python and OpenCV. It covers various applications of OpenCV, including image
manipulation, brightness and contrast adjustments, filtering with Sobel, Gaussian, and Laplacian
methods, kernel-based convolution for smoothing, and background replacement with solid colors.
The code examples demonstrate fundamental concepts, such as reading, displaying, and
saving images, applying transformations, and filtering images using kernels and masks. The
exercises provide hands-on experience in areas like edge detection, noise reduction, and
background modification, highlighting the versatility of OpenCV for image processing tasks.
This module effectively bridges theory and practice, making it a valuable resource for
understanding image processing fundamentals with Python and OpenCV

You might also like