Laboratory Activity 5
Laboratory Activity 5
Elective 3
Score
Submitted by:
Group 1
Antoni, Austine C.
Atencia, Dan Eric B.
Bauyon, Jared Randalle B.
Jao, Steven Rey C.
Leonardo, Aibel Renzo T.
Saturday, 7AM-4PM / CPE 0332.1-1
Date Submitted
11-08-2024
Submitted to:
I. Objectives
This laboratory activity aims to implement the principles and techniques of image segmentation through
MATLAB/Octave and open CV using Python
II. Methods
- Copy and paste your MATLAB code (use the original picture file: flower.jpg)
% figure(1);
imshowpair(img, bw, 'montage');
title('Original Image (left) and Binary Image (right)');
% % Segment the image into two regions using the imquantize function, specifying the threshold level
returned by the multithresh function.
% seg_img = imquantize(img,level);
% % Create a binary image using the computed threshold and display the image
% bw = imbinarize(img,T);
% figure(3);
imshow(bw);
title('Binary Image');
%%
% % 2. Region-based segmentation
%%
% % Paramter Modifications
% % Segment the image into two regions using the imquantize function, specifying the threshold level
returned by the multithresh function.
% seg_img = imquantize(img_noise,level);
% % Segment the image into two regions using k-means clustering RGB = imread('paris.jpg');
L = imsegkmeans(RGB,2); B = labeloverlay(RGB,L);
figure(7);
imshow(B);
title('Labeled Image');
% Create a set of 24 Gabor filters, covering 6 wavelengths and 4 orientations wavelength = 2.^(0:5) * 3;
orientation = 0:45:135;
g = gabor(wavelength,orientation);
% Filter the grayscale image using the Gabor filters. Display the 24 filtered images in a montage
gabormag = imgaborfilt(bw_RGB,g);
figure(8);
montage(gabormag,"Size",[4 6])
% Smooth each filtered image to remove local variations. Display the smoothed images in a montage
for i = 1:length(g)
sigma = 0.5*g(i).Wavelength;
gabormag(:,:,i) = imgaussfilt(gabormag(:,:,i),3*sigma); end
figure(9);
montage(gabormag,"Size",[4 6])
% Get the x and y coordinates of all pixels in the input image nrows = size(RGB,1);
ncols = size(RGB,2);
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
% Segment the image into two regions using k-means clustering with the supplemented feature set
L2 = imsegkmeans(featureSet,2,"NormalizeInput",true); C = labeloverlay(RGB,L2);
figure(10);
imshow(C);
title("Labeled Image with Additional Pixel Information");
B. Supplementary Activity
- plt.show()
-
- # Global Histogram Thresholding Using Otsu's Method
- counts, bins = np.histogram(grayImg.flatten(), bins=16, range=(0, 255)) # MATLAB:
imhist(, 16)
- otsuThresh = cv2.threshold(grayImg, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)[0] # MATLAB: otsuthresh(counts)
- _, bwOtsu = cv2.threshold(grayImg, otsuThresh, 255, cv2.THRESH_BINARY) # MATLAB:
imbinarize(, T)
-
- plt.figure(3)
- plt.imshow(bwOtsu, cmap='gray')
- plt.title('Binary Image')
- plt.show()
-
- # Region-Based Segmentation Using K-Means
- bwImg = cv2.cvtColor(cv2.imread('flower.jpg'), cv2.COLOR_BGR2GRAY)
-
- kMeans = KMeans(n_clusters=3, random_state=0).fit(bwImg.reshape(-1, 1)) # MATLAB:
imsegkmeans(, 3)
- labels = kMeans.labels_.reshape(bwImg.shape)
- labelOverlay = cv2.applyColorMap(np.uint8(labels * 255 / 2), cv2.COLORMAP_JET) #
MATLAB: labeloverlay(, L)
-
- plt.figure(4)
- plt.imshow(labelOverlay)
- plt.title('Labeled Image')
- plt.show()
-
- # Connected-Component Labeling
- _, binImg2 = cv2.threshold(bwImg, otsuThresh, 255, cv2.THRESH_BINARY) # MATLAB:
imbinarize()
- numLabels, labeledImg = cv2.connectedComponents(binImg2) # MATLAB:
bwlabel(bin_img2)
- coloredLabels = cv2.applyColorMap(np.uint8(labeledImg * 255 / numLabels),
cv2.COLORMAP_JET) # MATLAB: label2rgb(labeledImage, 'hsv', 'k', 'shuffle')
-
- print('Number of connected components: ', numLabels) # MATLAB: disp(['Number of
connected components: ', num2str(numberOfComponents)])
-
- plt.figure(5)
- plt.imshow(coloredLabels)
- plt.title('Labeled Image')
- plt.show()
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
-
- # Adding Noise and Segmentation
- noiseImg = np.clip(grayImg + np.random.normal(0, 25, grayImg.shape), 0,
255).astype(np.uint8) # MATLAB: imnoise(, 'salt & pepper', 0.09)
- otsuThreshNoise = filters.threshold_otsu(noiseImg) # MATLAB: multithresh(img_noise)
- _, segImgNoise = cv2.threshold(noiseImg, otsuThreshNoise, 255, cv2.THRESH_BINARY) #
MATLAB: imbinarize(, level)
-
- plt.figure(6)
- plt.subplot(1, 2, 1), plt.imshow(noiseImg, cmap='gray'), plt.title('Noisy Image')
- plt.subplot(1, 2, 2), plt.imshow(segImgNoise, cmap='gray'), plt.title('Segmented
Image with noise')
- plt.show()
-
- # Segmenting the image into two regions using K-Means clustering
- kMeans = KMeans(n_clusters=2, random_state=0).fit(img.reshape(-1, 3)) # MATLAB:
imsegkmeans(RGB, 2)
- labels = kMeans.labels_.reshape(img.shape[:2])
- labelOverlay = cv2.applyColorMap(np.uint8(labels * 255 / 2), cv2.COLORMAP_JET) #
MATLAB: labeloverlay(RGB, L)
-
- plt.figure(7)
- plt.imshow(labelOverlay)
- plt.title('Labeled Image')
- plt.show()
-
- # Creating and Applying Gabor Filters
- def gaborFilter(img, wavelength, orientation):
- filters = []
- for theta in orientation:
- theta = np.deg2rad(theta)
- for lambda_ in wavelength:
- kernel = cv2.getGaborKernel((31, 31), 4.0, theta, lambda_, 0.5, 0,
cv2.CV_32F) # MATLAB: gabor(wavelength, orientation)
- filters.append(kernel)
- return filters
-
- wavelength = [2 ** i * 3 for i in range(6)] # MATLAB: 2.^(0:5) * 3
- orientation = list(range(0, 180, 45)) # MATLAB: 0:45:135
- gaborKernels = gaborFilter(grayImg, wavelength, orientation)
-
- gaborMag = np.zeros_like(grayImg, dtype=np.float32)
- for kernel in gaborKernels:
- filteredImg = cv2.filter2D(grayImg, cv2.CV_32F, kernel)
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
III. Results
MATLAB
Python
- This Thresholding technique works by finding the threshold that minimizes the
intra-class variance (a variance within the foreground and background pixel intensities)
and assumes that the image contains two classes of pixels (foreground and
background). It then calculates the optimal threshold that separates the two classes. In
the given result, defined boundaries can be seen in the image processed using this
thresholding technique, including the borders of the coins and the images atop the
coins.
- This technique extends the original Otsu’s technique to segment an image into
multiple classes instead of just two. It works by finding multiple thresholds that
minimize the intra-class variance for each class, effectively separating the image into
several regions based on pixel intensity. Based on this technique's results, the
definitions in the borders and the images on the coins are much more detailed than
global thresholding.
- This method is used to convert a grayscale image into a binary image by finding an
optimal threshold. It then analyzes the histogram of the image to determine a threshold
that minimizes the intra-class variance. It then assumes that the image contains two
distinct classes of pixels and calculates the threshold that best separates these classes.
The computed threshold is then applied globally across the entire image to segment it
into foreground and background. The result of this technique is comparable to those
being shown using multi-level thresholding.
Region-Based Segmentation
1. K-means clustering
2. Connected-component labelling
Parameter Modification
<You can modify it to explore other functionalities>
% % Parameter Modifications
% % Segment the image into two regions using the imquantize function, specifying the threshold
level returned by the multithresh function.
% seg_img = imquantize(img_noise,level);
L = imsegkmeans(RGB,2);
B = labeloverlay(RGB,L);
figure(7);
imshow(B);
title('Labeled Image');
% Filter the grayscale image using the Gabor filters. Display the 24 filtered images in a montage
gabormag = imgaborfilt(bw_RGB,g);
figure(8);
montage(gabormag,"Size",[4 6])
% Smooth each filtered image to remove local variations. Display the smoothed images in a
montage
for i = 1:length(g)
sigma = 0.5*g(i).Wavelength;
gabormag(:,:,i) = imgaussfilt(gabormag(:,:,i),3*sigma);
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
end
figure(9);
montage(gabormag,"Size",[4 6])
% Segment the image into two regions using k-means clustering with the supplemented feature
set
L2 = imsegkmeans(featureSet,2,"NormalizeInput",true); C = labeloverlay(RGB,L2);
figure(10);
imshow(C);
title("Labeled Image with Additional Pixel Information");
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
Python
import cv2
import numpy as np
from matplotlib import pyplot as plt
from sklearn.cluster import KMeans
from skimage import color, filters
plt.figure(6)
plt.subplot(1, 2, 1), plt.imshow(noiseImg, cmap='gray'), plt.title('Noisy Image')
plt.subplot(1, 2, 2), plt.imshow(segImgNoise, cmap='gray'), plt.title('Segmented Image
with noise')
plt.show()
plt.figure(7)
plt.imshow(labelOverlay)
plt.title('Labeled Image')
plt.show()
filters = []
for theta in orientation:
theta = np.deg2rad(theta)
for lambda_ in wavelength:
kernel = cv2.getGaborKernel((31, 31), 4.0, theta, lambda_, 0.5, 0,
cv2.CV_32F)
filters.append(kernel)
return filters
plt.figure(8)
num_kernels = len(gaborKernels)
for i in range(num_kernels):
plt.subplot(4, 6, i + 1)
plt.imshow(cv2.filter2D(grayImg, cv2.CV_32F, gaborKernels[i]), cmap='gray')
plt.suptitle('Gabor Filtered Images')
plt.show()
plt.figure(9)
for i in range(num_kernels):
plt.subplot(4, 6, i + 1)
plt.imshow(gaborMag, cmap='gray')
plt.suptitle('Smoothed Gabor Filtered Images')
plt.show()
labels = kMeans.labels_.reshape(grayImg.shape)
labelOverlay = color.label2rgb(labels, image=img, bg_label=0)
plt.figure(10)
plt.imshow(labelOverlay)
plt.title('Labeled Image with Additional Pixel Information')
plt.show()
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
MATLAB:
Python:
MATLAB:
The code begins by loading an image file called 'flower.jpg' and determining whether it is a colored image; if
so, it changes it to grayscale using rgb2gray. In Otsu's method of global image thresholding, a global threshold
is determined for the grayscale image using graythresh, which is then utilized to convert the image to binary
form using imbinarize, allowing the original and binary images to be displayed together. Multi-level
thresholding is done by computing several thresholds using multithresh, segmenting the image into areas
using imquantize, and showing both the original and segmented images. For global histogram thresholding,
the code computes the grayscale image's histogram with imhist, then uses otsuthresh to determine the global
threshold from the histogram, and finally binarizes the image. The region-based segmentation method divides
the grayscale image into three regions using k-means clustering with imsegkmeans, labels the connected
components in the binary image with bwlabel, and assigns various colors to each connected component with
label2rgb. The code also shows parameter changes by applying salt-and-pepper noise to the grayscale image
with imnoise, followed by segmentation using Otsu's approach and k-means clustering on the original-colored
image. Finally, the Gabor filter is applied by first constructing a set of 24 Gabor filters with gabor, then
applying these filters to the grayscale image with imgaborfilt, smoothing the filtered images, then segmenting
the image using k-means clustering with additional pixel information.
Python:
The code starts by importing key libraries including OpenCV for image processing, NumPy for numerical
operations, Matplotlib for plotting, and Scikit-image for image processing functions. The image 'flower.jpg'
is loaded and transformed into the BGR format—this will be useful since Matplotlib read an image in RGB
format. Then, if img has 3 channels, it is then converted to grayscale. The method developed by Otsu’s
thresholding is then used to generate a binary image, which is shown alongside the original grayscale image.
K-Means clustering is applied to the grayscale image in three clusters, resulting to a segmented image that is
also presented. A grayscale image histogram is calculated, and Otsu's approach is used to calculate the binary
segmentation threshold, which is also displayed. The grayscale image is then segmented using three K-Means
clusters, and the color-mapped tagged image is shown. The binary image is then examined to discover
connected components, which are color-mapped and shown along with the number of related components.
Gaussian noise is introduced into the grayscale image, and Otsu's approach is used again to segment the noisy
image, which is exhibited alongside the original noisy image. The original image is also segmented using K-
Means clustering with two clusters, and the resulting image is color-mapped and shown. A custom Gabor
filter function is defined, which produces Gabor filters with varying wavelengths and orientations. These
filters are then applied to the grayscale image, resulting to a Gabor magnitude image that is presented. The
Gabor magnitude image is further smoothed with Gaussian blur, and the resulting images are presented.
Finally, a feature set containing the grayscale picture, Gabor magnitude, and pixel coordinates is generated
and reshaped for K-Means clustering, yielding a labeled image with additional pixel information that is color-
mapped and shown.
IV. Conclusion
In this activity, we have learned how to get the binary of an image using global thresholding, global histogram,
and multi-level thresholding. We have also manipulated an image using K-means, improved K-means using
Texture and Spatial, component labelling, component labelling with additional pixel information, adding salt
and pepper noise to a binary image, and different levels of Gabor and smooth Gabor filtered images. All of
these were done using MATLAB and Python.
Generally, the functionalities of the MATLAB and Python programs were closely aligned in their image
processing tasks like global thresholding, region-based segmentation, and Gabor filter analysis. However,
there were significant differences in the methods used for multi-level thresholding, noise addition, and
thresholding approaches.
PAMANTASAN NG LUNGSOD NG MAYNILA
(University of the City of Manila)
Intramuros, Manila
References
[1] D.J.D. Sayo. “University of the City of Manila Computer Engineering Department Honor Code,” PLM-
CpE Departmental Policies, 2020.