Error using fread and imageparser - matlab

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]);

Related

MATLAB - 'lib\sift\bin\siftfeat' is not recognized as an internal or external command, operable program or batch file

% thresholds used for g2NN test
dr2 = 0.5;
extract_feat = 1; % by default extract SIFT features using Hess' code
if(exist('filesift','var') && ~strcmp(filesift,'nofile'))
extract_feat = 0;
end
tic; % to calculate proc time
%C:\python36\Disso\sift-forensic-master
if extract_feat
sift_bin = fullfile('lib','sift','bin','siftfeat'); % e.g. 'lib/sift/bin/siftfeat' in linux
[pf,nf,ef] = fileparts(filename);
desc_file = [fullfile(pf,nf) '.txt'];
im1=imread(filename);
if (size(im1,1)<=1000 && size(im1,2)<=1000)
status1 = system([sift_bin ' -x -o ' desc_file ' ' filename]);
else
status1 = system([sift_bin ' -d -x -o ' desc_file ' ' filename]);
end
if status1 ~=0
error('error calling executables');
end
% import sift descriptors
[num, locs, descs] = import_sift(desc_file);
system(['rm ' desc_file]);
else
% import sift descriptors
[num, locs, descs] = import_sift(filesift);
end
if (num==0)
p1=[];
p2=[];
tp=[];
else
p1=[];
p2=[];
num=0;
% load data
loc1 = locs(:,1:2);
%scale1 = locs(:,3);
%ori1 = locs(:,4);
des1 = descs;
% descriptor are normalized with norm-2
if (size(des1,1)<15000)
des1 = des1./repmat(sqrt(diag(des1*des1')),1,size(des1,2));
else
des1_norm = des1;
for j= 1 : size(des1,2)
des1_j = des1_norm(j,:);
des1_norm(j,:) = des1_j/norm(des1_j,2);
end
des1 = des1_norm;
end
% sift matching
des2t = des1'; % precompute matrix transpose
if size(des1,1) > 1 % start the matching procedure iff there are at least 2 points
for i = 1 : size(des1,1)
dotprods = des1(i,:) * des2t; % Computes vector of dot products
[vals,indx] = sort(acos(dotprods)); % Take inverse cosine and sort results
j=2;
while vals(j)<dr2* vals(j+1)
j=j+1;
end
for k = 2 : j-1
match(i) = indx(k);
if pdist([loc1(i,1) loc1(i,2); loc1(match(i),1) loc1(match(i),2)]) >10
p1 = [p1 [loc1(i,2); loc1(i,1); 1]];
p2 = [p2 [loc1(match(i),2); loc1(match(i),1); 1]];
num=num+1;
end
end
end
end
tp = toc; % processing time (features + matching)
if size(p1,1)==0
fprintf('Found %d matches.\n', num);
else
p=[p1(1:2,:)' p2(1:2,:)'];
p=unique(p,'rows');
p1=[p(:,1:2)'; ones(1,size(p,1))];
p2=[p(:,3:4)'; ones(1,size(p,1))];
num=size(p1,2);
fprintf('Found %d matches.\n', num);
end
end
Hi all,
I have uploaded the code above for copy-move forgery detection. While running the code there are several errors which I am getting. I have also uploaded the snippet of the error that I am having trouble to fix with. I have also contacted the guy who wrote this code and he replied to me with following message: "You need to compile the third party library in the folder bin/sift accordingly to your operative system.".
I hope to find the solution here.
A snippet of the error

Matlab : Open previously saved figures and save as

I'm writing a Matlab code which plots and saves figures as png and eps.
h = figure(3);
plot(x,y)
xlabel('x'); ylabel('y');
FileName = sprintf('FileName.eps');
print(h,'-depsc', '-loose', FileName);
FileName = sprintf('FileName.png);
print(clhis,'-dpng', '-loose', FileName);
close(h)
I would like to just save them as FileName.fig for later process.
The function/script I would like to create would read all *.fig in current dir and save them as defined function.
Here is a pseudo function... But I'm not sure how to make it work properly!
function figureconvert(ext) % NOT WORKING! Just a mock up!
ext = 'eps';
Vector = READ ALL FIGS IN FOLDER;
for i = 1:length(Vector)
h = load Vector(i)
FileName = sprintf('FileName.%s',ext);
% print(h,'-d%sc', '-loose', FileName); ??
close(h)
end
end
I found a solution how to do this. Here is my function if someone else will need such function.
Just write:
figureconvert('png') or figureconvert('eps')
to convert *.fig to *.png or *.eps respectively.
function figureconvert(ext)
Files = dir('*.fig');
ext = ['.',ext]; ext = strrep(ext,'..','.');
for i = 1:length(Files)
figname = Files(i,1).name;
h = openfig(figname);
FigName = strrep(figname,'.fig',ext);
if strcmp(ext,'.eps')
print(h,'-depsc', '-loose', FigName);
elseif strcmp(ext,'.png')
print(h,'-dpng', '-loose', FigName);
end
close(h)
end
end

issues while using parfor in 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);

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

How to use reshape on a 4D matrix after using fread on a RGB RAW file?

The following code correctly loads an mp4 file and stores it in a 3D matrix.
r = 1;
fileName = testDummyMP4;
readerobj = VideoReader(fileName, 'tag', 'myreader1');
F = get(readerobj, 'numberOfFrames');
tampon = single(read(readerobj,1));
tampon = imresize(tampon(:,:,1),r);
I = zeros(size(tampon,1),size(tampon,2),F,'uint8');
for k = 1:F
disp(['Open: ' num2str(round(100*k/F)) '%'])
vidFrames = single(read(readerobj,k));
I(:,:,k) = imresize(vidFrames(:,:,2),r);
end;
imagesc((I(:,:,1)));
This is the output
I'm trying to reverse engineer this code so that it produces the same sort of result for but for a .raw 8bit rbg file. Following the answers from this question I tried the following:
You can download the 'M1302000245_1436389857.982603.raw' rbg file here
Or Google Drive version here
Ix = 256;
Iy = 256;
SF = 30; % Sample frequency
RecordingTime = 30;
Iz = SF*RecordingTime
testDummy = 'M1302000245_1436389857.982603.raw'
fin = fopen(testDummy, 'r');
I = fread(fin, Ix*Iy*3*Iz, 'uint8');
fclose(fin);
I = reshape(I, [Ix Iy 3 Iz]); % The rbg should be 256x256x3x900
% I've tried each of the following manipulations before calling imagesc to no avail
% I = flipdim(imrotate(I, -90),2);
% I=impixel(I)
% I=I'
imagesc((I(:,:,1))); % view first slice
This gives:
What am I doing wrong?
Additional info:
Recordings are taken using raspberry pi cameras with the following python code
class BrainCamera:
def __init__(self):
self.video_format = "rgb"
#self.video_quality = 5
# Set up the settings of the camera so that
# Exposure and gains are constant.
self.camera = picamera.PiCamera()
self.camera.resolution = (256,256)
self.camera.framerate = 30
sleep(2.0)
self.camera.shutter_speed = self.camera.exposure_speed
self.camera.exposure_mode = 'off'
g = self.camera.awb_gains
self.camera.awb_mode = 'off'
self.camera.awb_gains = g
self.camera.shutter_speed = 30000
self.camera.awb_gains = (1,1)
def start_recording(self, video_name_path):
self.camera.start_recording(video_name_path, format=self.video_format)
self.camera.start_preview()
def stop_recording(self):
self.camera.stop_recording()
self.camera.stop_preview()
# Destructor
def __del__(self):
print ("Closed Camera")
self.camera.close()
I don't get the output you have, but I get some reasonable image:
%your vode from above, ending with I=fread(...)
I=uint8(I)
I2=reshape(I, 3, Ix ,Iy, []);
I2=permute(I2,[3,2,1,4]);
imagesc(I2(:,:,:,1));
implay(I2);
With Daniel's help I got the following working. Additionally a co-worker found out how to get the number of frames of a .raw rbg video. This we needed since it turns out assuming noFrame = SF*RecordingTime was a bad idea.
testDummy = 'M1302000245_1436389857.982603.raw'
testDummyInfo = dir(testDummy);
noFrames = testDummyInfo.bytes/(256*256*3); % In my question Iz = noFrames
fin = fopen(testDummy, 'r');
I = fread(fin, testDummyInfo.bytes, 'uint8');
fclose(fin);
I=uint8(I);
I2=reshape(I, 3, Ix ,Iy, noFrames);
I2=permute(I2,[3,2,1,4]);
imagesc(I2(:,:,2,1)); % Throw out unnecessarry channels r and b. Only want GFP signal
to produce: