0% found this document useful (0 votes)
4 views38 pages

Dsp Reviwer

Uploaded by

Bernardo Coles
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)
4 views38 pages

Dsp Reviwer

Uploaded by

Bernardo Coles
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/ 38

ACTIVITY 2 - USING LIVE SCRIPT

Plotting
- Open New live script
- Select Text , then type “USING LIVESCRIPT IN MATLAB”.
Change the text format from “Normal” to “Title”.

CODE:
x = [0:0.2:2*pi] - if you see (where 0 < x < 2pi)
y = sin (x)
plot (x,y) - Plotting in Live script

You can divide your Live Script into sections.


Each section can then be run independently.
1. Create another section for cosine wave by clicking the “Section Break”
button in the Section Menu.

CODE:
x = [0:0.2:2*pi] - if you see (where 0 < x < 2pi)
z = cos (x)
plot (z,y) - Plotting in Live script
In MATLAB, we can represent a finite-duration sequence by a row vector
of appropriate values. However, such a vector does not have any
information about sample position n. Therefore, a correct
representation of x(n) would require two vectors, one each for x and n.
For example, a sequence:

x(n) = {2,1,-1,0,1,4,3,7}

can be represented in MATLAB by

>> n = [-3, -2, -1, 0, 1, 2, 3, 4]

>> x = [2, 1 -1, 0, 1, 4, 3, 7]


stem Function - The stem function in MATLAB creates a stem plot, which is a
type of plot that represents data as vertical lines (stems) originating from a baseline,
with markers at the data points. It is used to visualize discrete data or sequences.

In precise terms:

Purpose: It represents discrete data points clearly, showing their values on the y-axis
at specific x-axis positions.

Output: A stem plot, which consists of:

Vertical lines (stems) connecting the data points to a baseline (usually y=0)

xlim Function - The xlim function in MATLAB is used to set or query the limits of
the x-axis for a plot.

ylim Function - The ylim function in MATLAB is used to set or query the limits of
the y-axis for a plot.

The specific export options available under File > Export depend on the software
being used. Here are five common ways files can typically be exported across most
applications (e.g., Excel, Word, Photoshop, etc.):

Export as PDF
Converts the file to a Portable Document Format (PDF), which is widely used
for sharing documents with consistent formatting.

Export as Image (e.g., PNG, JPEG)


Saves the file as an image format for use in presentations, websites, or other
visual media.
Export as CSV or Text File
Converts the file data into a Comma-Separated Values (CSV) or plain text
format for use in other applications like databases or spreadsheets.

Export as a Video or Animation


For files involving motion (e.g., in Adobe Premiere or PowerPoint), the file
can be exported as a video format such as MP4.

Export to a Specific Application Format


Allows exporting the file into formats compatible with other software, such as
exporting to an older file version, HTML, or other proprietary formats.

ACTIVITY 1 - INTRODUCTION TO MATLAB


Pwd function - The pwd command in MATLAB displays the current working
directory, which is the folder where MATLAB reads and saves files by default.

Mkdir function- The command mkdir('Activity#1') creates a new folder named


Activity#1 in the current working directory.

mkdir('Activity#1'); % Create the folder


cd('Activity#1'); % Change to the new folder
save('sample.mat'); % Save workspace variables to sample.mat in Activity#1

Perform the following operations in the Command Window:


Basic arithmetic: 5 + 3, 7 * 2, 10 / 2, 3^2
Assign variables:
a = 10,
b = 20
Calculate c = a + b, d = a * b, e = sqrt(a + b)

disp() - to display the value of variable


Clear - When you use the clear command in MATLAB, it removes variables
from the workspace. clear all variables and check the workspace.

Clc - When you use the clc command in MATLAB, it clears the command
window.

a = 10,
b = 20

>> sqrt(a+b)

ans = 5.4772

MATLAB - operates on matrices (hence the name, “MATrix LABoratory”).


Matrices - are array of numbers. They are used to represent various quantities.
Vectors - one dimensional matrices, either a row matrix or column matrix
Identifier - is a name given to a variable that holds a certain value
10 ≤ x ≤ 10 = x = [-10 : 10]
a) grid on

Feature Added: It adds a grid to the plot.

Description: The grid lines make it easier to read the values of the plot
by displaying horizontal and vertical grid lines across the axes.

b) axis([-10 10 -35 35])

Feature Added: It sets the limits of the x-axis and y-axis.

Description: The x-axis will range from -10 to 10, and the y-axis will
range from -35 to 35. This command allows you to focus on a specific
portion of the plot.

c) xlabel("x")

Feature Added: It adds a label to the x-axis.

Description: The label "x" will be displayed along the x-axis, which
helps identify what the x-axis represents.

d) ylabel("y")

Feature Added: It adds a label to the y-axis.

Description: The label "y" will be displayed along the y-axis, which
helps identify what the y-axis represents.

e) title("Sample Plot")

Feature Added: It adds a title to the plot.

Description: The title "Sample Plot" will be displayed at the top of the
plot, providing a descriptive heading for the plot.

f) clf

Feature Added: It clears the current figure window.

Description: This command removes all graphics, resetting the figure


window. Any existing plot in the figure will be erased, and the figure is
ready for new plotting.
a) plot(x, y, 'b')

 Feature Added: Plots the data with a blue solid line.


 Description: The 'b' specifies the color blue, and the default line
style is solid. This will display a plot with a blue line connecting
the points defined by the x and y data.

b) plot(x, y, '--')

 Feature Added: Plots the data with a dashed line.


 Description: The '--' specifies that the line connecting the points
should be dashed rather than solid. This is useful for distinguishing
different data series or styles in a plot.

c) plot(x, y, '-o')

 Feature Added: Plots the data with a solid line and circle
markers at each data point.
 Description: The '-' specifies a solid line, and the 'o' adds circular
markers at each data point. This makes it easier to see the
individual data points on the plot.

d) plot(x, y, '-.xg')

 Feature Added: Plots the data with a dash-dot line, 'x' markers,
and green color.
 Description:

o '-.' specifies a dash-dot line style.


o 'x' specifies the use of 'x' markers at each data point.
o 'g' specifies the color green for the line and markers.

Summary of Markers and Colors:


 Line Styles:
o '-': Solid line
o '--': Dashed line
o '-.': Dash-dot line
 Markers:

o 'o': Circle marker


o 'x': Cross marker
o Others: '+' (plus sign), '*' (asterisk), '.' (point)

 Colors:

o 'b': Blue
o 'g': Green
o 'r': Red
o 'k': Black
o 'm': Magenta
o 'c': Cyan
o 'y': Yellow

y = 3.5.^(-0.5*x) .* cos(6*x) for -2 ≤ x ≤ 4


>> x = [-2: 1: 4]
x = Columns 1 through 4 -2 -1 0 1 Columns 5 through 7 2 3 4

>> y = 3.5.^(-0.5*x) .* cos(6*x)


y = Columns 1 through 2 2.9535 1.7963 Columns 3 through 4 1.0000 0.5132
Columns 5 through 6 0.2411 0.1008 Column 7 0.0346

>> plot (x,y)


ACTIVITY 3 : RECORD AUDIO

>> recObj = audiorecorder


recObj = audiorecorder with properties: SampleRate: 8000 BitsPerSample: 8 NumChannels: 1
DeviceID: -1 CurrentSample: 1 TotalSamples: 0 Running: 'off' StartFcn: [] StopFcn: [] TimerFcn:
[] TimerPeriod: 0.0500 Tag: '' UserData: [] Type: 'audiorecorder' BitsPerSample is ignored in
MATLAB Online.
>> recObj = audiorecorder(44100,16,2);
>> recDuration = 5;
>> disp("Begin Speaking")
Begin Speaking
>> recordblocking(recObj,recDuration);

>> disp("End of Recording");


End of Recording
>> play(recObj);
>> y = getaudiodata(recObj);
>> plot(y);

1. recObj = audiorecorder

 This creates an audiorecorder object with default settings:


o SampleRate = 8000 Hz (samples per second)
o BitsPerSample = 8 (audio bit depth)
o NumChannels = 1 (mono sound)
o DeviceID = -1 (default audio input device)
 The recObj object is used for audio recording and playback.

2. recObj = audiorecorder(44100,16,2);

 This creates an audiorecorder object with custom settings:


o SampleRate = 44100 Hz (CD-quality audio)
o BitsPerSample = 16 (higher-quality audio with more detail)
o NumChannels = 2 (stereo sound)
 The recObj object is now configured for high-quality stereo recording.

3. recDuration = 5;

 Sets the recording duration to 5 seconds.


 The variable recDuration specifies how long the recording should last.
4. disp("Begin Speaking")

 Displays the message "Begin Speaking" in the Command Window.


 This is a signal for the user to start speaking, as the recording is about to
begin.

5. recordblocking(recObj,recDuration);

 Starts recording audio for 5 seconds (recDuration).


 The function blocks MATLAB's execution until the recording is complete. This
means MATLAB waits for 5 seconds before moving to the next line of code.

6. disp("End of Recording");

 Displays the message "End of Recording" in the Command Window.


 This informs the user that the recording has ended.

7. play(recObj);

 Plays back the recorded audio stored in recObj.


 This allows you to immediately hear the sound you recorded.

8. y = getaudiodata(recObj);

 Extracts the recorded audio data from the recObj object and stores it in the
variable y.
 y is a numeric array containing the amplitude values of the recorded audio.

9. plot(y);

 Plots the audio data stored in y.


 The x-axis represents time (in terms of sample indices), and the y-axis
represents the amplitude of the audio signal.
 This visualization helps you analyze the waveform of the recorded audio.

What happens when you change the value of the sample rate?
The sample rate determines how many audio samples are captured per second.
Changing it affects:

Higher Sample Rate (e.g., 44100 Hz, 96000 Hz):

Better Quality: Captures more details and higher frequencies (up to half
the sample rate, per Nyquist theorem).

Larger File Size: More data points are stored.Used for music, high-
fidelity audio

Lower Sample Rate (e.g., 8000 Hz, 16000 Hz):

Lower Quality: Captures fewer details and lower frequencies.

Smaller File Size: Less data to store.

Suitable for speech, telephony, or low-bandwidth applications.

Impact on Plots: Higher sample rates produce smoother waveforms, while lower
ones appear jagged due to fewer data points.

Choose Based on Application:

 44100 Hz: CD-quality music.


 8000 Hz: Speech or phone calls.

TASK 1:
1. Record two 10-seconds voice signal. (Use a sample rate of 44,100 Hz, 8-bit depth,
and one audio
channel).
2. Play the recorded audio simultaneously.

CODE:

>> % Record first audio signal


>> recObj1 = audiorecorder(44100, 8, 1);
>> disp("Begin Speaking for Audio 1");
>> recordblocking(recObj1, 10);
>> disp("End of Recording for Audio 1");

>> % Record second audio signal


>> recObj2 = audiorecorder(44100, 8, 1);
>> disp("Begin Speaking for Audio 2");
>> recordblocking(recObj2, 10);
>> disp("End of Recording for Audio 2");

>> % Retrieve audio data


>> audio1 = getaudiodata(recObj1);
>> audio2 = getaudiodata(recObj2);

>> % Play both audios simultaneously


>> disp("Playing both audios simultaneously...");
>> sound(audio1, 44100); % Play first audio
>> pause(0.1); % Small delay to ensure they start almost at the same time
>> sound(audio2, 44100); % Play second audio

USING SUBPLOT
>> subplot (2,1,1);
>> plot (audio1);
>> title ('First Signal');
>> xlabel('Sample Number');
>> ylabel('Amplitude');

>> subplot (2,1,2);


>> plot (audio2);
>> title ('Second Signal');
>> xlabel('Sample Number');
>> ylabel('Amplitude');

SIGNAL PLOTTING AND MANIPULATION

ADDITION
>> subplot (2,2,1);
>> plot (audio1);
>> title ('First Signal');
>> xlabel('Sample Number');
>> ylabel('Amplitude');

>> subplot(2,2,2);
>> plot(audio2);
>> title ('Second Signal');
>> xlabel('Sample Number');
>> ylabel ('Amplitude')

>> signal_sum = (audio1 + audio2);


>> subplot (2,2,3);
>> plot(signal_sum);
>> title ('Sum of Two Signals');
>> xlabel('Sample Number');
>> ylabel('Amplitude');

SUBTRACTION
>> signal_sub = audio1 - audio2;
>> subplot(2, 3, 4);
>> plot(signal_sub);
>> title('Subtraction of Two Signals');
>> xlabel('Sample Number');
>> ylabel('Amplitude');
FLIPPING
>> flipped_audio2 = flip(audio2);
>> subplot(2, 3, 5);
>> plot(flipped_audio2);
>> title('Flipped Second Signal');
>> xlabel('Sample Number');
>> ylabel('Amplitude');

CONVOLUTION
>> signal_conv = conv(audio1, audio2);
>> subplot(2, 3, 6);
>> plot(signal_conv);
>> title('Convolution of Two Signals');
>> xlabel('Sample Number');
>> ylabel('Amplitude');

Convolution is a mathematical operation that is used in digital


signal processing to modify an audio signal. It is a process of
combining two signals to form a third signal. In the context of
audio processing, convolution is used to impart the
characteristic timbres of spaces and objects on other signals.
In audio production, convolution is used to create realistic
reverbs and other effects. The process involves working with
two audio sources: an input signal and an impulse response.
The input signal is the sound that will be affected, while the
impulse response contains the sonic characteristics of the space
or object that we will impart on the input signal.
MATLAB -MATrix LABoratory is a programming
platform designed specifically for engineers and
scientists to analyze and design systems and products
that transform our world
Matrix-Base Language , Super Powerful graphing calculator
- matrix manipulations, plotting of functions and data,
implementation of algorithms, creation of user interfaces, and
interfacing with programs written in other languages
- it was designed by Cleve Moler in the late 1970s and was
initially intended to be a simple interactive matrix calculator
• As of 2020, MATLAB has more than 4 million users worldwide.

CURRENT DIRECTORY - Shows the folder location


Important because saves files, run scripts and etc.

Workspace - displays all the variables that are currently


in the memory during your MATLAB sessions

Variable Names - names of the variable u have defined


Values - values assigned to the variables
Class (Type) - data type of each varaible (double etc.)
Size - Dimensions of the variable

Command Window - primarily interface where you can


directly enter commands, execute code and iteract with
MATLAB.

VARIABLE NAME RULES:


• First character MUST be a letter
• After that, any combination of numbers, letters, and _
• Names are CASE-SENSITIVE (e.g. var1 is different from Var1)
MATLAB is a “weakly typed” language
• MATLAB supports various types: the most popular ones:
• 3.84 (64-bit double-default)
• ‘A’ (16-bit character)
• Most variables you’ll deal with are vectors, matrices, doubles or
chars
• Other types: complex, symbolic, 16-bit and 8-bit integers, etc.
IMAGE PREPROCESSING
- is a crucial step in many image processing and computer
vision applications because it enhances the image data, making
it easier for algorithms to extract useful information or for visual
inspection.

IMAGE RESAMPLING
- is the process of changing the spatial resolution of an image
by interpolating or down-sampling pixel values.
- It’s commonly used for resizing images, such as scaling them
up or down, rotating them, or correcting geometric
distortions. Resampling allows us to adjust the number of
pixels in an image while preserving as much detail as possible.
Imresize - IS USED FOR IMAGE RESAMPLING
>> img = imread('moon.tif');
>> subplot(1,3,1);
>> imagesc(img);
>> title('moon.tif');
>> axis tight equal
>> subplot(3,3,2);
>> filt = fspecial("gaussian",[90,90], 3);
>> surf(filt);
>> title('Sigma \sigma = 3');
>> subplot(3,3,3);
>> filt_img = conv2(img, filt, "same");
>> imagesc(filt_img);
>> axis tight equal
>> title('Filtered Image');
>> subplot(3,3,5);
>> filt = fspecial("gaussian",[90,90], 9);
>> surf(filt);
>> title('Sigma \sigma = 9');
>> subplot(3,3,6);
>> filt_img = conv2(img, filt, "same");
>> imagesc(filt_img);
>> axis tight equal
>> subplot(3,3,8);
>> filt = fspecial("gaussian",[90,90], 15);
>> surf(filt);
>> title('Sigma \sigma = 15');
>> subplot(3,3,9);
>> filt_img = conv2(img,filt,"same");
>> imagesc(filt_img);
>> axis tight equal
COLOR IMAGE IN MATLAB
>> subplot(3,3,2);
>> img = imread('peppers.png');
>> imagesc(img);
>> title ('pepper.png');
>> axis tight equal
>> red = img(:,:,1);
>> green = img(:,:,2);
>> blue = img(:, :, 3);
>> subplot(3,3,4);
>> imagesc(red);
>> colormap("gray");
>> axis equal tight
>> title ('red channel');
>> subplot (3,3,7);
>> imhist(red);
>> subplot(3,3,5);
>> imagesc(green);
>> colormap("gray");
>> axis tight equal
>> title ('green channel');
>> subplot(3,3,8);
>> imhist(green);
>> subplot(3,3,6);
>> imagesc(blue);
>> colormap("gray");
>> axis tight equal
>> title ('blue channel');
>> subplot(3,3,9);
>> imhist(blue);
HSV COLOR SPACE

>> hsv_img = rgb2hsv (img);


>> hue = hsv_img(:, :, 1);
>> saturation = hsv_img(:, :, 2);
>> values = hsv_img(:, :, 3);
>> subplot(3,3,7);
>> imagesc(hue);
>> title ('hue');
>> axis tight equal
>> subplot(3,3,8);
>> imagesc(saturation);
>> title ('saturation');
>> axis tight equal
>> colormap ("gray");
>> subplot(3,3,9);
>> imagesc(values);
>> colormap("gray");
>> axis tight equal;
>> title ('values');
HISTOGRAM EQUALIZATION
>> subplot (2,2,1);
>> img = imread('tire.tif');
>> imagesc(img);
>> colormap ("gray");
>> axis tight equal
>> title ('tire.tif');
>> subplot(2,2,2);
>> imhist(img);
>> x = histeq(img);
>> subplot (2,2,3);
>> imagesc(x);
>> axis equal tight
>> title ('histogram equalized image');
>> subplot(2,2,4);
>> imhist(x);
INTERPOLATION METHODS
>> img = imread('cameraman.tif');
>> imagesc(img);
>> colormap("gray");
>> axis equal tight;
>> cropped_img = img(40:80, 95:135);
>> imagesc(cropped_img);
>> axis equal tight;
>> subplot(3,3,2);
>> imagesc(cropped_img);
>> axis equal tight;
>> x = imresize(cropped_img, 0.3, "nearest");
>> subplot (3,3,4);
>> imagesc(x);
>> axis equal tight;
>> title ('Downs Nearest');
>> y = imresize (cropped_img, 0.3,"bilinear");
>> subplot (3,3,5);
>> imagesc(y);
>> axis tight equal
>> title ('Down billinear');
>> z = imresize(cropped_img, 0.3, "bicubic");
>> subplot (3,3,6);
>> imagesc(z);
>> axis tight equal
>> title ('Down bicubic');
>> xx = imresize(cropped_img, 3, "nearest");
>> subplot (3,3,7);
>> imagesc(xx);
>> axis equal tight
>> title ('Up Nearest');
>> yy = imresize(cropped_img, 3, "bilinear");
>> subplot (3,3,8);
>> imagesc(yy);
>> axis tight equal
>> title ('Up billinear');
>> zz = imresize (cropped_img, 3, "bicubic");
>> subplot (3,3,9);
>> imagesc(zz);
>> axis tight equal
>> title ('Up bicubic');
SOBEL FILTER
>>img = imread("moon.tif");
>>figure;

% Display original image


>>subplot(2, 4, 1);
>>image(img);
>>axis equal tight;
>>colormap("gray");
>>title("moon.tif");

% Sobel filters
>>sobelh = fspecial("sobel");
>>sobelv = sobelh';

% Horizontal Sobel
>>subplot(2, 4, 2);
>>img_sobelh = conv2(double(img), sobelh, "same");
>>image(abs(img_sobelh), 'CDataMapping', 'scaled');
>>axis equal tight;
>>title("Horizontal Sobel");

% Vertical Sobel
>>subplot(2, 4, 3);
>>img_sobelv = conv2(double(img), sobelv, "same");
>>image(abs(img_sobelv), 'CDataMapping', 'scaled');
>>axis equal tight;
>>title("Vertical Sobel");
% Cropped Original
>>subplot(2, 4, 5);
>>image(img);
>>axis equal tight;
>>axis([130, 250, 360, 480]);

% Cropped Horizontal Sobel


>>subplot(2, 4, 6);
>>image(abs(img_sobelh), 'CDataMapping', 'scaled');
>>axis equal tight;
>>axis([130, 250, 360, 480]);

% Cropped Vertical Sobel


>>subplot(2, 4, 7);
>>image(abs(img_sobelv), 'CDataMapping', 'scaled');
>>axis equal tight;
>>axis([130, 250, 360, 480]);

% Gradient Magnitude and Enhanced Sobel


>>gradientmagnitude = sqrt((img_sobelh).^2 + (img_sobelv).^2);

% Display Enhanced Sobel


>>subplot(2, 4, 4);
>>img_sobel = double(img) + 0.5 * gradientmagnitude;
>>image(img_sobel, 'CDataMapping', 'scaled');
>>axis equal tight;

% Cropped Enhanced Sobel


subplot(2, 4, 8);
image(img_sobel, 'CDataMapping', 'scaled');
axis equal tight;
axis([130, 250, 360, 480]);
Intensity ThreshHolding

>> img = imread("cameraman.tif");


>> imshow(img);
>> subplot (1,3,1);
>> imshow(img);
>> subplot(2,2,2);
>> imhist(img);
>> binaryimg = img > 90;
>> subplot(2,2,4);
>> imshow (binaryimg);
Otsu's Threshold Method
>> subplot (2,2,3);
>> threshold = graythresh(img);
>> threshold*255
>> binary_img = imbinarize(img);
>> imshow(binary_img);
>> img2 = imbinarize(img, "adaptive");
>> subplot(2,2,1);
>> imshow (img2);
>> img2 = imbinarize(img, "adaptive", ForegroundPolarity="dark");
>> subplot(2,2,2);
>> imshow(img2);

Edge Detection

>> edges = edge(img, "canny");


>> subplot(2,2,4);
>> imshow(edges);
Text figure
>> img = imread("text.png");
>> imshow(img);
>> stats = regionprops(img, "BoundingBox");
>> stats.BoundingBox
>> for n = 1:length(stats);
text = stats(n).BoundingBox;
rectangle("Position", text, "EdgeColor", 'b', "LineWidth",1);
end
>> imshow(img);
>> for n = 1:length(stats);
coin = stats(n).BoundingBox;
rectangle("Position", coin, "EdgeColor", 'b', "LineWidth",1);
end
Detecting Connected Components
>> img = imread("coins.png");
>> imshow(img);
>> binaryimg = imbinarize(img);
>> imshow(binaryimg);
>> img2 = imfill(binaryimg, "holes");
>> imshow(img2);
>> cc.NumObjects - tocheck on how many connect components
>> stats = regionprops(img2, "BoundingBox");
>> stats.BoundingBox
>> coin1 = stats(1).BoundingBox
>> rectangle("Position", coin1, "EdgeColor", 'g', "LineWidth",2);
For Looping Coin 1-10
>> for n = 1:length(stats);
coin = stats(n).BoundingBox;
rectangle("Position", coin, "EdgeColor", 'b', "LineWidth",1);
end
>> imshow(img);
>> for n = 1:length(stats);
coin = stats(n).BoundingBox;
rectangle("Position", coin, "EdgeColor", 'b', "LineWidth",1);
end

You might also like