issues while using parfor in Matlab - matlab

How is it possible to resolve this error. As this video upload takes too much time. Firstly I am reading a cell. Then creating histogram of a frame extracted from video, then comparing it with any previous frame and uploading only if there is any significant difference between histograms.
global currRowIndex;
global histCell;
if (fname ~= 0)
file_fullpath = strcat(pthname, fname);
[pathstr, name, ext] = fileparts(file_fullpath);
mov=VideoReader(file_fullpath);
data = read(mov, Inf);
nFrames=mov.NumberOfFrames;
parfor k = 1: nFrames
waitbar(k/nFrames);
if(k==1)
index=currRowIndex;
cell=histCell;
currentFrame = read(mov, k);
imgHSV=rgb2hsv(currentFrame);
H = imgHSV(:,:,1);
S = imgHSV(:,:,2);
V = imgHSV(:,:,3);
hHist = hist(H(:),16);
sHist = hist(S(:),16);
vHist = hist(V(:),16);
index=index+1;
cell(index,:,:,:,index)={name;hHist;sHist;vHist;categorySelected};
else
currentFrame = read(mov, k);
imgHSV=rgb2hsv(currentFrame);
H = imgHSV(:,:,1);
S = imgHSV(:,:,2);
V = imgHSV(:,:,3);
hHist = hist(H(:),16);
sHist = hist(S(:),16);
vHist = hist(V(:),16);
[rowCurr,colCurr,depthCurr]=size(cell);
found=0;
if(row==0)
row=1;
end
for x=row:rowCurr
dbRow=cell(x,:,:,:,x);
H_Temp= getDiff(dbRow{2},hHist);
if(H_Temp>2000 && dbRow{5}==categorySelected)
found=1;
break;
end
end
if(found==1)
index=index+1;
cell(index,:,:,:,index)={name;hHist;sHist;vHist;categorySelected};
end
end
end
The error I get is as below
??? Reference to a cleared variable cell.
Error in ==> FrmUploadVideo>(parfor body) at 133
[rowCurr,colCurr,depthCurr]=size(cell);

Related

Plot graph with 2 variables in matlab

I'm planning to plot a graph of velocity against time using matlab. The change of time is 0.05 and total time 15. When time change, the graph will change and save a figure of that. I had mat file which contained all the data for time and velocity.
E.g, t=0, v=0, plot and save, t=0.05, v=1, plot and save until t=15.
I tried to use v=v+1 (which acts like i++) but failed to read the value of v in 2nd row. Any other method to do so?
Thank You.
The code is
i = 001
dt = t(2,1) - t(1,1);
k = dt*(i-1);
filename1 = 'front_data';
matFileName = sprintf('%s.mat', filename1);
matData = load(matFileName);
t = matData.time;
fv = matData.front_velocity;
fig = figure%('visible', 'off');
s = t(1,1);
fv = fv(1,1);
lot (s,fv,'*')
pic_filename = sprintf('front_data%02d.jpeg', k);
print(fig,pic_filename,'-djpeg')
istart = 002
iend = 301
for i = istart:iend
k = dt*(i-1);
t = t+dt
filename1 = 'front_data';
matFileName = sprintf('%s.mat', filename1);
matData = load(matFileName);
t = matData.time;
fv = matData.front_velocity;
v = fv(1,1);
v = v+1;
h = figure
axis([0 15 0 0.6])
plot(t,v,'*')
pic_filename = sprintf('front_data%02d.jpeg', k);
print(h,pic_filename,'-djpeg')
end
And the example I refer is the [https://www.mathworks.com/matlabcentral/answers/110632-how-to-increment-a-variable]
I reduced your example to the essential parts.
istart = 2;
iend = 301;
counter=istart;
%load data
% filename1 = 'front_data';
% matFileName = sprintf('%s.mat', filename1);
% matData = load(matFileName);
% t = matData.time;
% fv = matData.front_velocity;
%for demonstaration
t=0:.05:15;
fv=rand(size(t));
for i = istart:iend
%update
time = t(istart:counter);
values = fv(istart:counter);
%plot
plot(time,values,'*')
%increase index
counter=counter+1;
end
As you are loading always the same data in the loop you can do it once outside the loop, and for plotting you just update the length of your vector to be plotted. You could also just append the new value to the actual list.

Error using fread and imageparser

Hello when l run the code above l got this error . l don't where is the error ,my codes (.m) and training examples are in the same working directory.
Error using fread
Invalid file identifier. Use fopen to generate a valid file identifier.
Error in MNISTParser (line 3)
magic_number = fread(fp,1,'uint32',0,'b');
Error in MNIST_gen (line 2)
train_labels = MNISTParser('./MNIST/train-labels-idx1-ubyte');
MNIST_gen.m
clear
**train_labels = MNISTParser('./MNIST/train-labels-idx1-ubyte');**
train_images = MNISTParser('./MNIST/train-images-idx3-ubyte');
test_labels = MNISTParser('./MNIST/t10k-labels-idx1-ubyte');
test_images = MNISTParser('./MNIST/t10k-images-idx3-ubyte');
test_item_number = length(test_labels);
train_item_number = length(train_labels);
image_scale = size(test_images,2);
test_images_unfold = reshape(test_images,test_item_number,image_scale^2)';
test_labels_unfold = full(ind2vec(test_labels'+1));
train_images_unfold = reshape(train_images,train_item_number,image_scale^2)';
train_labels_unfold = full(ind2vec(train_labels'+1));
save MNIST.mat;
colormap(gray);
axis off
axis image
%show an image of a digit in test samples
for i=1:1
j=randi(length(test_labels),1);
image(reshape(255-test_images(j,:,:),28,28));
title(sprintf('%d',test_labels(j)));
pause(1);
image(reshape(test_images_unfold(:,j),28,28));
title(vec2ind(test_labels_unfold(:,j))-1);
pause(1);
end
%show an image of a digit in train samples
for i=1:1
j=randi(length(train_labels),1);
image(reshape(255-train_images(j,:,:),28,28));
title(sprintf('%d',train_labels(j)));
pause(1);
image(reshape(train_images_unfold(:,j),28,28));
title(vec2ind(train_labels_unfold(:,j))-1);
pause(1);
end
MNISTParser.m
function res = MNISTParser(filename)
fp = fopen(filename,'r');
**magic_number = fread(fp,1,'uint32',0,'b');**
items_number = fread(fp,1,'uint32',0,'b');
if 2049==magic_number
res = fread(fp,items_number,'uint8',0,'b');
else
if 2051==magic_number
img_rows = fread(fp,1,'uint32',0,'b');
img_cols = fread(fp,1,'uint32',0,'b');
res = zeros(items_number,img_rows,img_cols);
for i=1:items_number
res(i,:,:) = fread(fp,[img_cols,img_rows],'uint8',0,'b')';
end
else
error('wrong magic number');
end
end
fclose(fp);
end
Thanks for helps
l find the mistake. it is related to the extension of the files.
here is the instruction that has helped me to find out my mistake [fp,msg] = fopen(filename,'r');
if fp<1, error([msg ' File: ' filename]);

wav_to_audio custom function is not working

At my wit's end. This program used to work for me, but now for some reason I keep getting that I cannot open the file. (Was using the same file before and no problem). I tried to just switch to wavread only and it worked but it added all sorts of complications for me to debug throughout the rest of my program, so I'd really like to get wav_to_audio working again.
The error message is
Error using wavread (line 70) Invalid Wave File. Reason: Cannot open file.
Error in wav_to_audio (line 108) [f_audio,fs,nbits] = wavread(strcat(dirAbs,dirRel,wavfilename));
Error in test_TempogramToolbox (line 61) [audio,sideinfo] = wav_to_audio('',dirWav,filename);
Here is the matlab code:
clear close all
dirWav = 'data_wav/';
filename = 'Debussy_SonataViolinPianoGMinor-02_111_20080519-SMD-ss135-189.wav';
% filename = '110-130bpm_click.wav';
% filename = 'Faure_Op015-01_126_20100612-SMD-0-12.wav';
% filename = 'Poulenc_Valse_114_20100518-SMD-0-15.wav';
% filename = 'Schumann_Op015-03_113_20080115-SMD-0-13.wav';
%% load wav file, automatically converted to Fs = 22050 and mono
[audio,sideinfo] = wav_to_audio('',dirWav,filename); Fs = sideinfo.wav.fs;
%% wav_to_audio function
if parameter.message == 1
fprintf('wav_to_audio: processing %s, ',wavfilename);
end
[pathstr,name,ext] = fileparts(wavfilename);
if strcmp(ext,'.wav')
[f_audio,fs,nbits] = wavread(strcat(dirAbs,dirRel,wavfilename));
else
error(['Unknown file format ' ext]);
end
bConverted_to_mono = 0;
if parameter.convertToMono
if size(f_audio,2)>1
bConverted_to_mono = 1;
if parameter.message == 1
fprintf('converting to mono, ');
end
switch parameter.monoConvertMode
case 'leftmost_channel'
f_audio= f_audio(:,1);
case 'rightmost_channel'
f_audio= f_audio(:,size(f_audio,2));
case 'downmix' % pay attention to energy loss due to differences in phase
% when using this method. This is often the case for bad
% stereo mixes
nChannels = size(f_audio,2);
f_audio = sum(f_audio,2);
f_audio = f_audio / nChannels;
otherwise
disp('wav_to_audio: monoConvertMode : Unknown method')
end
end
end
bResampled = 0;
if parameter.useResampling
if (fs ~= parameter.destSamplerate)
bResampled = 1;
if parameter.message == 1
fprintf('Resampling to %d, ', parameter.destSamplerate);
end
f_audio = resample (f_audio,parameter.destSamplerate,fs,100);
fs = parameter.destSamplerate;
end
end
%% Update sideinfo
sideinfo.wav.version = 1;
sideinfo.wav.filename = wavfilename;
sideinfo.wav.dirRel = dirRel;
sideinfo.wav.size = size(f_audio,1);
sideinfo.wav.duration = (sideinfo.wav.size-1)/fs;
sideinfo.wav.energy = sum(f_audio.^2);
sideinfo.wav.fs = fs;
sideinfo.wav.nbits = nbits;
sideinfo.wav.channels = size(f_audio,2);
sideinfo.wav.resampled = bResampled;
sideinfo.wav.monoConverted = bConverted_to_mono;
if bConverted_to_mono
sideinfo.wav.monoConvertMode = parameter.monoConvertMode;
else
sideinfo.wav.monoConvertMode = 'none';
end
%% Saving data
if parameter.save == 1
if parameter.message == 1
fprintf('Saving to file, ');
end
filename = strcat(parameter.saveFilename,'_audio');
save(strcat(parameter.saveDir,filename),'f_audio','sideinfo');
end
if parameter.message == 1
fprintf('Done\n');
end
%% Visualization
if parameter.vis
figure;
for k=1:sideinfo.wav.channels
if sideinfo.wav.channels > 1
subplot(sideinfo.wav.channels,1,k);
end
plot( [0:sideinfo.wav.size-1] / sideinfo.wav.fs , f_audio(:,k));
axis tight;
end
end
end

Subscripted assignment dimension mismatch in matlab

I executed this code using Feature Matrix 517*11 and Label Matrix 517*1. But once the dimensions of matrices change the code cant be run. How can I fix this?
The error is:
Subscripted assignment dimension mismatch.
in this line :
edges(k,j) = quantlevels(a);
Here is my code:
function [features,weights] = MI(features,labels,Q)
if nargin <3
Q = 12;
end
edges = zeros(size(features,2),Q+1);
for k = 1:size(features,2)
minval = min(features(:,k));
maxval = max(features(:,k));
if minval==maxval
continue;
end
quantlevels = minval:(maxval-minval)/500:maxval;
N = histc(features(:,k),quantlevels);
totsamples = size(features,1);
N_cum = cumsum(N);
edges(k,1) = -Inf;
stepsize = totsamples/Q;
for j = 1:Q-1
a = find(N_cum > j.*stepsize,1);
edges(k,j) = quantlevels(a);
end
edges(k,j+2) = Inf;
end
S = zeros(size(features));
for k = 1:size(S,2)
S(:,k) = quantize(features(:,k),edges(k,:))+1;
end
I = zeros(size(features,2),1);
for k = 1:size(features,2)
I(k) = computeMI(S(:,k),labels,0);
end
[weights,features] = sort(I,'descend');
%% EOF
function [I,M,SP] = computeMI(seq1,seq2,lag)
if nargin <3
lag = 0;
end
if(length(seq1) ~= length(seq2))
error('Input sequences are of different length');
end
lambda1 = max(seq1);
symbol_count1 = zeros(lambda1,1);
for k = 1:lambda1
symbol_count1(k) = sum(seq1 == k);
end
symbol_prob1 = symbol_count1./sum(symbol_count1)+0.000001;
lambda2 = max(seq2);
symbol_count2 = zeros(lambda2,1);
for k = 1:lambda2
symbol_count2(k) = sum(seq2 == k);
end
symbol_prob2 = symbol_count2./sum(symbol_count2)+0.000001;
M = zeros(lambda1,lambda2);
if(lag > 0)
for k = 1:length(seq1)-lag
loc1 = seq1(k);
loc2 = seq2(k+lag);
M(loc1,loc2) = M(loc1,loc2)+1;
end
else
for k = abs(lag)+1:length(seq1)
loc1 = seq1(k);
loc2 = seq2(k+lag);
M(loc1,loc2) = M(loc1,loc2)+1;
end
end
SP = symbol_prob1*symbol_prob2';
M = M./sum(M(:))+0.000001;
I = sum(sum(M.*log2(M./SP)));
function y = quantize(x, q)
x = x(:);
nx = length(x);
nq = length(q);
y = sum(repmat(x,1,nq)>repmat(q,nx,1),2);
I've run the function several times without getting any error.
I've used as input for "seq1" and "seq2" arrays such as 1:10 and 11:20
Possible error might rise in the loops
for k = 1:lambda1
symbol_count1(k) = sum(seq1 == k);
end
if "seq1" and "seq2" are defined as matrices since sum will return an array while
symbol_count1(k)
is expected to be single value.
Another possible error might rise if seq1 and seq2 are not of type integer since they are used as indexes in
M(loc1,loc2) = M(loc1,loc2)+1;
Hope this helps.

Local thresholding in MATLAB

I am trying to implement local thresholding in MATLAB 7.7. This is what my original image looks like:
As seen the the word Test is covered in black. This image is a PNG image having dimensions 919x551. I want to apply local thresholding to this image so that I can get the word Test to be visible clearly.
I have implemented the following code that works by dividing the entire image into sub images of 60*60 blocks.
However, when I am doing so, I am not getting the desired output.
My code:
clc;
clear all;
close all;
im = imread('C:\samples\test100.png');
subplot(3,3,1);
imshow(im);
title('original image');
im = rgb2gray(im);
im = double(im);
subplot(3,3,2);
imshow(im);
title('gray scale image');
[row col] = size(im);
max_im = max(max(im));
h = zeros(1,max_im+1);
!1st block
for n = 1:1:60
for m = 1:1:60
a(n,m) = im(n,m);
end
end
a = a+1;
for n = 1:1:60
for m = 1:1:60
t = a(n,m);
h(t) = h(t)+1;
end
end
subplot(3,3,3);
bar(h)
[X,Y] = ginput(1);
for n = 1:1:60
for m = 1:1:60
if a(n,m)<X
a(n,m) = 0;
else
a(n,m) = 255;
end
end
end
subplot(3,3,4);
imshow(uint8(a))
title('1st block image');
!2nd block
for n = 1:1:60
for m = 61:1:60
b(n,m-60) = im(n,m)
end
end
b = b+1;
for n = 1:1:60
for m = 1:1:60
t = b(n,m);
h(t) = h(t)+1;
end
end
figure(2)
bar(h)
[X,Y] = ginput(1);
for n = 1:1:60
if b(n,m)<X
b(n,m) = 0;
else
b(n,m) = 255;
end
end
imshow(uint8(b))
!3rd block
for n = 61:1:120
for m = 1:1:60
c(n-60,m) = im(n,m);
end
end
c = c+1;
for n = 1:1:60
for m = 1:1:60
t = c(n,m);
h(t) = h(t)+1;
end
end
figure(3)
bar(h)
[X,Y] = ginput(1);
for n = 1:1:60
for m = 1:1:60
if c(n,m)< X
c(n,m) = 0;
else
c(n,m) = 255;
end
end
end
imshow(uint8(c))
!final block
for n = 1:1:row
for m = 61:1:col
d(n-60,m-60) = im(n,m);
end
end
d = d+1;
for n = 1:1:60
for m = 1:1:60
t = d(n,m);
h(t) = h(t)+1;
end
end
figure(4);
bar(h);
[X,Y] = ginput(1);
for n = 1:1:60
for m = 1:1:60
if d(n,m)<X
d(n,m) = 0;
else
d(n,m) = 255;
end
end
end
imshow(uint8(d))
s = [a b;c d];
figure(5);
imshow(uint(s))
When I try to run the entire code I get an error as:
??? Undefined function or method 'local' for input arguments of type 'char'
However, when I run only the code for the 1st block I get the following output.
How will I get the word Test visible by creating sub-images and then merging them together?
You can scan the greyscale image horizontally and then find the position of non-zero (or above the threshold) values and set that interval to be filled with white (256 or 1 if using im2double).
for j=1:551
row = im(:,j)
test = 0;
im2=zeros(size(im))
i=0;
%Left black area
while (test == 0 && i<919)
im2(i,j)=0;
if row(i)>threshold
test=1;
end;
i=i+1;
end;
%White inner area
while (test == 1 && i<919)
im2(i,j)=1
if row(i)>threshold
test=0;
end;
i=i+1;
end;
%Left black area
while (i<919)
im2(i,j)=0;
i=i+1;
end;
This doesn't work with letters that have an empty area (such as 'p'), but you can modify the code a little to do that.