How to make MATLAB play an array faster? - arrays

I'm working on a audio processor, which is supposed to change the pitch and add a vibrato to a song while it is playing. Note that, although the sound isn't live (e.g. from a microphone) the effects that I want to add are to be made in real time.
I found that the best way to approach it would be dividing the soundfile into small elements and apply the effects on each one by order.
So I wrote this to divide the audio file:
%Load Sound File
[fsample Fs] = wavread ('C:\Users\Ogulcan\Desktop\Bitirme Projesi\Codes\kravitz.wav');
%length of the sample
t=length(fsample);
%number of samples
ns=10;
%Defining the array:
A=[];
%Create the vectors and place them into the array 'A':
for i=1:ns-1
v=fsample(i*t/ns:(i+1)*t/ns);
A=[A;v];
end
This code works and divides the sound into 10 samples, however when I try to play them in a loop there is a small but noticable delay. Now I plan on doing this for a lot bigger sample numbers.
Can anyone help me with this speed issue? I really don't know any other language than MATLAB or have the required software, so I would appreciate if you could show me a way to do this in MATLAB.

You can replace the entire loop with the following simpler snippet:
A = fsample(1:end-rem(length(fsample),ns)); % ensure data has ns full samples
A = reshape(A,[],ns)';

Related

LMS implementation in LabVIEW fpga (High throughput personality)

Have to say surprised with the limitations of labVIEW FPGA in array implementation. I am not experienced enough in labview to make this comment but I found it very difficult to work with arrays !!.
I am working on Active Noise Cancellation project. I need to collect audio data from two microphones #40k Sample rate and 100 samples per frame (at least) and output the audio through loud speaker #40k sample rate. For this purpose, I am using myRIO 1900 in FPGA High throughput personality.
Right now, I am trying to implement LMS algorithm in LabVIEW FPGA platform. I have attached the MATLAB code below, what I want to implement !
Till array intializations are fine but when it comes to temporary vector manipulations. like :
x_temp(1:nr_c-1)=x_temp(2:nr_c);
x_temp(nr_c)=x(i);
I am going mad ! How to do this ? LabVIEW doesnt allow us to index the 1D arrays properly ( we can only extract one particular element of array not part of array, I can extract x_temp(1:nr_c) with sub array function but how to extract x_temp(2:nr_c) ??)
Please help me how to do the manipulation of 'x_temp' vector with the above basic statements.
PS: 1.LabVIEW FPGA supports only one dimensional array operations.
Even though Adaptive Filter Toolkit pallettes are available in myRIO FPGA High throughput personality, I cannot install Adaptive Filter Toolkit on myRIO Target.!!!
3.In MyLMS program : x : input vector(Array) , y: Desired Signal, nr_c : number of filter coefficients ,step: step size. I hope you understood the rest program :)
MyLMS.m :
function [y_hat,e,w] = MyLms(step, nr_c, x, y)
%intializing all vectors
coeffs=zeros(1,nr_c);
x_temp=zeros(1,nr_c);
y_hat=zeros(length(x),1);
e=zeros(length(x),1);
for i=1:length(x)
%temporary vector formation
x_temp(1:nr_c-1)=x_temp(2:nr_c);
x_temp(nr_c)=x(i);
%LMS algorithm iterations
y_hat(i) = x_temp * coeffs';
e(i)= y(i) - y_hat(i);
coeffs = coeffs+step*e(i)*x_temp;
end
I am by no means a LabVIEW FGPA expert, but I think you would encounter very similar limitations in VHDL.
At any rate, the typical technique for accessing subarrays is using rotate and replace subset (see Joel_G's post). For more information about the FPGA constraints and capabilities, see the help document: Array Palette Details (FPGA Module).

Repairing pixelated image using matlab Help needed

http://i.imgur.com/j7hStIG.png
Hi I need help repairing this image using for loops. I know I have to identify the bad pixels first and fill them in. thanks. PS I am very new to matlab
clear
clc
format compact
filenameIN = uigetfile('.bmp','Picture');
noisyRGBarray = imread(filenameIN);
figure(1)
imshow(noisyRGBarray)
y = noisyRGBarray;
[m,n]=size(y)
clean=[];
for i=2:m-1
for j=2:n-1
if y(i,j)% clean add new
clean = [ clean, y(i,j) ]
end
end
end
Im pretty sure the for statemetn is wrong and I do not know wat to do from here. I need help writing the for loop to go through the image matrix to identify the black and white pixels.
Try running a median filter on your image. See here for an example.
If you must use a for loop for learning reasons, please explain what you consider to be a "bad pixel" (black? different from neighbors in some way?), attempt to identify such a pixel based on the criteria you settle on, and adjust the value of that pixel.
In general, you should not adopt the approach of starting with an empty array and growing it one pixel at a time. Rather, create the output image as a copy of the input (clean=noisyRGBarray;) or initialize with zeros (clean=zeros(size(noisyRGBarray))), and modify the bad pixels (clean(i,j,:)=...);

Is there a C lib to find peaks in noisy data equivalent to findPeaks.m

i have a noisy set of data and want to find the peaks in it. There is a matlab function for this exact task which includes smoothing of the data. I is called findpeaks.m
Now as im working in C i would either would have to code this by myself or use some functions which im not aware of. I hope you can tell me if they exist and where i can find them, as this is a very common problem.
To be clear what im searching of: a function to first smooth my data and then calculate the peaks, both preferably with some parameters for smoothing method, peak width etc.
Thanks!

Image/2D array resampling in C

I am looking to implement a resampling algorithm for a 2D array(it could be grayscale image or some 2D array of floating point values).
The steps involved in this particular operation are:
Given a 2D array, I first downsample it to size of 8x8 or 16x16, using some down-sampling method(preferably with a preceeding anti-aliasing filtering).
Some nuemrical operation on this.
Then upsample it back to its original size by doing, bilinear interpolation.
As a prototype I coded it as shown below in Octave. It gives decent results. I am looking to get some reference on C implementation.
fid = fopen("anti_vig_gain_map.txt","r");
fid2 = fopen("ds_us_anti_vig_gain_map.txt","w");
for i=1:1968
for j=1:2592
map(i,j) = fscanf(fid,'%f\n',1);
end
end
%downsample
ds_map = imresize(map,[8 8],'linear');
%% some processing on ds_map
%upsample
us_map = imresize(ds_map,[1968 2592],'linear');
I tried to see the code in imresize.m but it gets complicated after sometime and could not extract C code out of it.
Any pointers to reference C code for bilinear interpolation to perform the upsampling.
Also looking to get some pointers for the the anti-aliasing filter and down-sampling method using bilinear method.
I think what you are looking for is contained in the NetPBM suite. Specifically, pamscale which handles both up and down sampling with multiple possible filtering schemes for both directions. The code is both well-written and self-contained.

Given an audio stream, find when a door slams (sound pressure level calculation?)

Not unlike a clap detector ("Clap on! clap clap Clap off! clap clap Clap on, clap off, the Clapper! clap clap ") I need to detect when a door closes. This is in a vehicle, which is easier than a room or household door:
Listen: http://ubasics.com/so/van_driver_door_closing.wav
Look:
It's sampling at 16bits 4khz, and I'd like to avoid lots of processing or storage of samples.
When you look at it in audacity or another waveform tool it's quite distinctive, and almost always clips due to the increase in sound pressure in the vehicle - even when the windows and other doors are open:
Listen: http://ubasics.com/so/van_driverdoorclosing_slidingdoorsopen_windowsopen_engineon.wav
Look:
I expect there's a relatively simple algorithm that would take readings at 4kHz, 8 bits, and keep track of the 'steady state'. When the algorithm detects a significant increase in the sound level it would mark the spot.
What are your thoughts?
How would you detect this event?
Are there code examples of sound pressure level calculations that might help?
Can I get away with less frequent sampling (1kHz or even slower?)
Update: Playing with Octave (open source numerical analysis - similar to Matlab) and seeing if the root mean square will give me what I need (which results in something very similar to the SPL)
Update2: Computing the RMS finds the door close easily in the simple case:
Now I just need to look at the difficult cases (radio on, heat/air on high, etc). The CFAR looks really interesting - I know I'm going to have to use an adaptive algorithm, and CFAR certainly fits the bill.
-Adam
Looking at the screenshots of the source audio files, one simple way to detect a change in sound level would be to do a numerical integration of the samples to find out the "energy" of the wave at a specific time.
A rough algorithm would be:
Divide the samples up into sections
Calculate the energy of each section
Take the ratio of the energies between the previous window and the current window
If the ratio exceeds some threshold, determine that there was a sudden loud noise.
Pseudocode
samples = load_audio_samples() // Array containing audio samples
WINDOW_SIZE = 1000 // Sample window of 1000 samples (example)
for (i = 0; i < samples.length; i += WINDOW_SIZE):
// Perform a numerical integration of the current window using simple
// addition of current sample to a sum.
for (j = 0; j < WINDOW_SIZE; j++):
energy += samples[i+j]
// Take ratio of energies of last window and current window, and see
// if there is a big difference in the energies. If so, there is a
// sudden loud noise.
if (energy / last_energy > THRESHOLD):
sudden_sound_detected()
last_energy = energy
energy = 0;
I should add a disclaimer that I haven't tried this.
This way should be possible to be performed without having the samples all recorded first. As long as there is buffer of some length (WINDOW_SIZE in the example), a numerical integration can be performed to calculate the energy of the section of sound. This does mean however, that there will be a delay in the processing, dependent on the length of the WINDOW_SIZE. Determining a good length for a section of sound is another concern.
How to Split into Sections
In the first audio file, it appears that the duration of the sound of the door closing is 0.25 seconds, so the window used for numerical integration should probably be at most half of that, or even more like a tenth, so the difference between the silence and sudden sound can be noticed, even if the window is overlapping between the silent section and the noise section.
For example, if the integration window was 0.5 seconds, and the first window was covering the 0.25 seconds of silence and 0.25 seconds of door closing, and the second window was covering 0.25 seconds of door closing and 0.25 seconds of silence, it may appear that the two sections of sound has the same level of noise, therefore, not triggering the sound detection. I imagine having a short window would alleviate this problem somewhat.
However, having a window that is too short will mean that the rise in the sound may not fully fit into one window, and it may apppear that there is little difference in energy between the adjacent sections, which can cause the sound to be missed.
I believe the WINDOW_SIZE and THRESHOLD are both going to have to be determined empirically for the sound which is going to be detected.
For the sake of determining how many samples that this algorithm will need to keep in memory, let's say, the WINDOW_SIZE is 1/10 of the sound of the door closing, which is about 0.025 second. At a sampling rate of 4 kHz, that is 100 samples. That seems to be not too much of a memory requirement. Using 16-bit samples that's 200 bytes.
Advantages / Disadvantages
The advantage of this method is that processing can be performed with simple integer arithmetic if the source audio is fed in as integers. The catch is, as mentioned already, that real-time processing will have a delay, depending on the size of the section that is integrated.
There are a couple of problems that I can think of to this approach:
If the background noise is too loud, the difference in energy between the background noise and the door closing will not be easily distinguished, and it may not be able to detect the door closing.
Any abrupt noise, such as a clap, could be regarded as the door is closing.
Perhaps, combining the suggestions in the other answers, such as trying to analyze the frequency signature of the door closing using Fourier analysis, which would require more processing but would make it less prone to error.
It's probably going to take some experimentation before finding a way to solve this problem.
You should tap in to the door close switches in the car.
Trying to do this with sound analysis is overengineering.
There are a lot of suggestions about different signal processing
approaches to take, but really, by the time you learn about detection
theory, build an embedded signal processing board, learn the processing
architecture for the chip you chose, attempt an algorithm, debug it, and then
tune it for the car you want to use it on (and then re-tune and re-debug
it for every other car), you will be wishing you just stickey taped a reed
switch inside the car and hotglued a magnet to the door.
Not that it's not an interesting problem to solve for the dsp experts,
but from the way you're asking this question, it's clear that sound
processing isn't the route you want to take. It will just be such a nightmare
to make it work right.
Also, the clapper is just an high pass filter fed into a threshold detector. (plus a timer to make sure 2 claps quickly enough together)
There is a lot of relevant literature on this problem in the radar world (it's called detection theory).
You might have a look at "cell averaging CFAR" (constant false alarm rate) detection. Wikipedia has a little bit here. Your idea is very similar to this, and it should work! :)
Good luck!
I would start by looking at the spectral. I did this on the two audio files you gave, and there does seem to be some similarity you could use. For example the main difference between the two seems to be around 40-50Hz. My .02.
UPDATE
I had another idea after posting this. If you can, add an accelerometer onto the device. Then correlate the vibrational and acoustic signals. This should help with cross vehicle door detection. I'm thinking it should be well correlated since the sound is vibrationally driven, wheres the stereo for example, is not. I've had a device that was able to detect my engine rpm with a windshield mount (suction cup), so the sensitivity might be there. (I make no promises this works!)
(source: charlesrcook.com)
%% Test Script (Matlab)
clear
hold all %keep plots open
dt=.001
%% Van driver door
data = wavread('van_driver_door_closing.wav');
%Frequency analysis
NFFT = 2^nextpow2(length(data));
Y = fft(data(:,2), NFFT)/length(data);
freq = (1/dt)/2*linspace(0,1,NFFT/2);
spectral = [freq' 2*abs(Y(1:NFFT/2))];
plot(spectral(:,1),spectral(:,2))
%% Repeat for van sliding door
data = wavread('van_driverdoorclosing.wav');
%Frequency analysis
NFFT = 2^nextpow2(length(data));
Y = fft(data(:,2), NFFT)/length(data);
freq = (1/dt)/2*linspace(0,1,NFFT/2);
spectral = [freq' 2*abs(Y(1:NFFT/2))];
plot(spectral(:,1),spectral(:,2))
The process for finding distinct spike in audio signals is called transient detection. Applications like Sony's Acid and Ableton Live use transient detection to find the beats in music for doing beat matching.
The distinct spike you see in the waveform above is called a transient, and there are several good algorithms for detecting it. The paper Transient detection and classification in energy matters describes 3 methods for doing this.
I would imagine that the frequency and amplitude would also vary significantly from vehicle to vehicle. Best way to determine that would be taking a sample in a Civic versus a big SUV. Perhaps you could have the user close the door in a "learning" mode to get the amplitude and frequency signature. Then you could use that to compare when in usage mode.
You could also consider using Fourier analysis to eliminate background noises that aren't associated with the door close.
Maybe you should try to detect significant instant rise in air pressure that should mark a door close. You can pair it with this waveform and sound level analysis and these all might give you a better result.
On the issue of less frequent sampling, the highest sound frequency which can be captured is half of the sampling rate. Thus, if the car door sound was strongest at 1000Hz (for example) then a sampling rate below 2000Hz would lose that sound entirely
A very simple noise gate would probably do just fine in your situation. Simply wait for the first sample whose amplitude is above a specified threshold value (to avoid triggering with background noise). You would only need to get more complicated than this if you need to distinguish between different types of noise (e.g. a door closing versus a hand clap).

Resources