Hi de,
To convert signals to spectrogram images and save them as JPG files, adjust your MATLAB script to handle file paths and image saving correctly. Use fullfile to construct file paths robustly. Load each .mat file, assuming val contains the signal, and process the desired portion. Denoise the signal using "ddencmp" and "wdencmp". Set the sampling frequency and use pspectrum to generate the spectrogram.
Use figure('Visible', 'off') to create figures invisibly and saveas to save each spectrogram as a JPG in a directory like Spectrograms. Ensure this directory exists by using "mkdir('Spectrograms')" before the loop. Close each figure with "close(gcf)" after saving to manage memory efficiently. This automates converting multiple signals to spectrogram images without manual intervention.
The below code snippet demonstrates the key changes in the code:
% Define the path to the .mat files
Path = 'IS\*.mat';
Files = dir(Path);
% Loop through each file
for i = 1:length(Files)
% Construct the full file name and load the .mat file
fn = fullfile(Files(i).folder, Files(i).name);
load(fn);
% Assuming 'val' is the variable containing the signal
y = val(1:3600);
% Denoise the signal
[thr, sorh, keepapp] = ddencmp('den', 'wv', y);
sig1 = wdencmp('gbl', y, 'sym10', 10, thr, sorh, keepapp);
% Define sampling frequency
fs = 128;
% Generate and display the spectrogram
figure('Visible', 'off'); % Create a figure without displaying it
pspectrum(sig1, fs, 'spectrogram', 'TimeResolution', 0.5);
title(['Spectrogram of Signal ', num2str(i)]);
% Save the spectrogram as a JPG file
temp = fullfile('Spectrograms', [num2str(i, '%04d'), '.jpg']);
saveas(gcf, temp);
close(gcf); % Close the figure after saving
end
For more details, please refer to the following MathWorks documentation:
- wdencmp - https://www.mathworks.com/help/wavelet/ref/wdencmp.html
- ddencmp - https://www.mathworks.com/help/wavelet/ref/ddencmp.html
Hope this helps!