I have recently started working in mexopencv and I am new to it. However, I have made a database of keypoints and features of images for ORB and SURF and saved it in a .mat file along with the trained matchers.
Matcher used:
FLANN based matcher (for SURF points)
BruteForce - Hamming (for ORB points)
It works fine if I train the data in the same script and try to find the image from the databse. However, when I try to find the image from the database in another script by loading the keypoints data and the matcher, it fails.
The code for making database is:
%% OPTIONS
SURF_Threshold = 40000;
%% SETUP
SURF = cv.SURF('HessianThreshold', SURF_Threshold);
ORB = cv.ORB;
opts = {'KDTree', 'Trees',5}; %Dictionary required for FLANN
matcherFLANN = cv.DescriptorMatcher('FlannBasedMatcher', 'Index',opts);
matcherBF = cv.DescriptorMatcher('BruteForce-Hamming');
foldername = uigetdir;
oldFolder = cd(foldername);
files = [dir('*.jpg');dir('*.png')]; %Look for jpg files in the directory.
N = size(files,1); %numel the files
%Create empty training sets
trainDataORB = struct('name', cell(N,1), 'pts',cell(N,1), 'feat',cell(N,1));
trainDataSURF = struct('name', cell(N,1), 'pts',cell(N,1), 'feat',cell(N,1));
%% TRAINING
for i=1:N
% read image
img = imread((files(i).name));
%Extracting keypoints and descriptors (features) for both
[trainDataSURF(i).pts, trainDataSURF(i).feat] = SURF.detectAndCompute(img);
[trainDataORB(i).pts, trainDataORB(i).feat] = SURF.detectAndCompute(img);
trainDataSURF(i).name = files(i).name;
trainDataORB(i).name = files(i).name;
% add to training set to match against for each of descriptor
matcherFLANN.add(trainDataSURF(i).feat);
matcherBF.add(trainDataORB(i).feat);
end
% build index
matcherFLANN.train();
matcherBF.train();
%% SAVING DATA
%Navigate back to old folder
cd(oldFolder);
save('training_data.mat', 'matcherFLANN', 'matcherBF', 'trainDataSURF','trainDataORB');
The matcher objects are then loaded with in another scrip (with cleared workspace):
load('training_data.mat');
Which returns the error:
Error using DescriptorMatcher_ Object not found id=109
Error in cv.DescriptorMatcher/match (line 461)
matches = DescriptorMatcher_(this.id, 'match', queryDescriptors, varargin{:});
Error in detection_Test (line 27)
matches = matcherFLANN.match(feat);
Any help would be gladly welcomed.
Related
i just following 'Perform Instance Segmentation Using Mask R-CNN' example
URL : "https://kr.mathworks.com/help/vision/ug/example-InstanceSegmentationUsingMaskRCNNDeepLearningExample.html"
I have download the file(instances_train2014.json, cocoapi-master, unpackAnnotations.m(was in helper file) )
but i don't know how to compling gason.
enter image description here
so i get a error, matlab can not read coco annotation file
enter image description here
i just copy the example code and change the file path
matlab 2022b
%download traindata
imageFolder = fullfile(dataFolder,"images");
captionsFolder = fullfile(dataFolder,"annotations");
if ~exist(imageFolder,"dir")
mkdir(imageFolder)
mkdir(captionsFolder)
end
annotationFile = fullfile(captionsFolder,"instances_train2014.json");
str = fileread(annotationFile);
%read and process training data
trainClassNames = ["person","car"];
numClasses = length(trainClassNames);
imageSizeTrain = [800 800 3];
cocoAPIDir = fullfile(dataFolder,"cocoapi-master","MatlabAPI");
addpath(cocoAPIDir);
unpackAnnotationDir = fullfile(dataFolder,"annotations_unpacked","matFiles");
if ~exist(unpackAnnotationDir,'dir')
mkdir(unpackAnnotationDir)
end
helper.unpackAnnotations(trainClassNames,annotationFile,imageFolder,unpackAnnotationDir);
%create data
i want to train coco dataset but i don't know c++ compling
what is the gason complie..?
how can i get complied annodation data with gason..?
After extracting HOG features of folder of images, I want to add all this results in one matrix. How I can do this? this is my code in matlab:
% Get list of all jpg files in this directory
% DIR returns as a structure array. You will need to use () and . to get
% the file names.
%to get all images in Motorbikes directory
imagefiles = dir('Motorbikes/*.jpg');
nfiles = length(imagefiles); % Number of files found
for ii=1:nfiles
currentfilename = ['Motorbikes/',imagefiles(ii).name];
currentimage = imread(currentfilename);
images{ii} = currentimage;
end
%To extract features of each image
featureMatrix = [];
for jj=1:nfiles
currentImageFeatures = extractHOGFeatures(images{jj});
featureMatrix = [featureMatrix, currentImageFeatures];
end
I am in the process of building a KNN algorithm with the purpose of identifying and categorizing common engine problems in Matlab. I have been using the builds from the book 'An Introduction To audio Analysis: A Matlab Approach' which contains exactly what I need to continue my experiment. The problem is that when I identify where the audio samples are kept on my computer, the system claims that it gives out the message "audio sample path is not valid!" Below is the original algorithm the authors of the book have supplied
function kNN_model_add_class(modelName, className, classPath, ...
listOfStatistics, stWin, stStep, mtWin, mtStep)
%
% function kNN_model_add_class(modelName, className, classPath, ...
% listOfStatistics, stWin, stStep, mtWin, mtStep)
%
% This function adds an audio class to the kNN classification model
%
% ARGUMENTS;
% - modelName: the filename of the model (mat file)
% - className: the name of the audio class to be added to the model
% - classPath: the path of the directory where the audio segments of the
% new class are stored
% - listOfStatistics: list of mid-term statistics (cell array)
% - stWin, stStep: short-term window size and step
% - mtWin, mtStep: mid-term window size and step
%
% Example:
% kNN_model_add_class('modelSpeech.mat', 'speech', './Music/', ...
% {'mean','std',}, 0.050, 0.025, 2.0, 1.0);
%
if ~exist(classPath,'dir')
error('Audio sample path is not valid!');
else
classPath = [classPath filesep];
end
% check if the model elaready exists:
fp = fopen(modelName, 'r');
if fp>0 % check if file already exists
load(modelName);
end
% Feature extraction:
D = dir([classPath '*.wav']);
F = [];
for (i=1:length(D)) % for each wav file in the given path:
curFileName = [classPath D(i).name];
FileNamesTemp{i} = curFileName;
% mid-term feature extraction for each wav file:
midFeatures = featureExtractionFile(curFileName, ...
stWin, stStep, mtWin, mtStep, listOfStatistics);
% long-term averaging:
longFeatures = mean(midFeatures,2);
F = [F longFeatures];
end
% save the model:
Statistics = listOfStatistics;
fp = fopen(modelName, 'r');
if fp<0 % model does not exist --> generate
ClassNames{1} = className;
Features{1} = F;
FileNames{1} = FileNamesTemp;
save(modelName, 'ClassNames', 'Features', ...
'Statistics', 'stWin', 'stStep', 'mtWin', 'mtStep', 'FileNames');
else
load(modelName);
ClassNames{end+1} = className;
Features{end+1} = F;
FileNames{end+1} = FileNamesTemp;
save(modelName, 'ClassNames', 'Features', ...
'Statistics', 'stWin', 'stStep', 'mtWin', 'mtStep', 'FileNames');
end
Here is the way that I have implemented it into my own project.
%Knn algorithm training
%path to folder containing the audio segements
strDir ='/Users/itsolutions/Documents/MATLAB/Wav_engine_edits ';
%mid-term statistics to be used:
Statistics = {'mean','median','std','stdbymean','max','min'};
%short-term and mid-term, processing windon length and step:
stWin = 0.040; stStep = 0.040;
mtWin = 2.0; mtStep = 1.0;
%perform feature extraction
kNN_model_add_class ('model8.mat','connection rod noise', [ strDir '/Connection_rod_edits/'],Statistics, stWin, stStep, mtWin, mtStep);
kNN_model_add_class ('model8.mat','detonation noise', [strDir ' /Detonation_noise_edits/'],Statistics, stWin, stSteo, mtWin, mtStep)
%kNN_model_add_class ('model8.mat','Engine bearing noise' [strDir '/Engine Bearing Noise edits/'],Statistics, stWin, stStep, mtWin, mtStep);
Any ideas? I have looked into the objects present in the function knn_model_add_class() and have found that it is still using wavread, which in the 2016b version of matlab in invalid syntax now.
Could anyone give me a hand? Seems like I am going in circles and it is something really obvious that i can't see.
Regards
M.Brown
Edit:
Using the process of elimination I have found that the error comes from this piece of code
if ~exist(classPath,'dir')
error('Audio sample path is not valid!');
else
classPath = [classPath filesep];
end
The code cannot seem to find the audio samples in question. I have contacted the author of the book, but until then does anybody know why the matlab file path won't recognize the wav files?
I am new in image processing and I want help. I have a folder (dataset) that contains 1000 images and I want to insert noise 'salt & pepper' with different density noise (0.01,0.02 and 0.03) , I used this line to do this:
im = imread('C:\Users\SAMSUNG\Desktop\AHTD3A0002_Para1.tif');
J = imnoise(im,'salt & pepper',0.01);
Please help me to do this : I want to save the result in 3 folder ( data1 contains images after noise with d=0.01, data2 contains images after noise with d=0.02 and data3 contains images after noise with d=0.03).
any suggestation and thanks in advance
Following code will allow you to select the folder and create the noised pictures in 3 different folders. It will only select the '*.tif' files which you can modify in the code. And if you need to create more noise levels, create a loop to name the folders and files dynamically.
% get dir
folderX = uigetdir();
% get files
picFiles = dir('*.tif');
% loop over the files and save them with the noise
for ii = 1:length(picFiles)
currentIm = imread([folderX, '\', picFiles(ii).name]);
% create folders if not exist
if ~exist([folderX,'\noise_0.01\'], 'dir')
% create folders
mkdir([folderX,'\noise_0.01\']);
end
if ~exist([folderX,'\noise_0.02\'], 'dir')
% create folders
mkdir([folderX,'\noise_0.02\']);
end
if ~exist([folderX,'\noise_0.03\'], 'dir')
% create folders
mkdir([folderX,'\noise_0.03\']);
end
J1 = imnoise(currentIm,'salt & pepper',0.01);
imwrite(J1,fullfile([folderX, '\noise_0.01\', picFiles(ii).name]));
J2 = imnoise(currentIm,'salt & pepper',0.02);
imwrite(J2,fullfile([folderX, '\noise_0.02\', picFiles(ii).name]));
J3 = imnoise(currentIm,'salt & pepper',0.03);
imwrite(J3,fullfile([folderX, '\noise_0.03\', picFiles(ii).name]));
end
An easy solution with 2 for loop.
%save the noise parameter.
noise = [0.01,0.02,0.03];
for i = 1:1000
%we generate the filename (you can adapt this code)
imname = fullfile('C:\Users\SAMSUNG\Desktop\',sprintf('AHTD3A0002_Para%d.tif',i))
%read the image.
im = imread(imname);
for j = 1:length(noise)
%apply the noise
J = imnoise(im,'salt & pepper',noise(j));
%save image in the right folder
imwrite(J,fullfile('C:\Users\SAMSUNG\Desktop',sprintf('folder%d',j)));
end
end
My code is below. In the code, I am evaluating only the data in the 'fb2010' file. I want to add other files" 'fb2020', 'fb2030', and 'fb2040' and evaluate their data by the same code. My question is how to apply a for loop and include the other data files. I tried, but I got confused by the for loop.
load('fb2010'); % loading the data
x = fb2010(3:1:1502,:);
% y_filt = filter(b,a,x); % filtering the received signal
y_filt= filter(b,a,x,[],2);
%%%%%%% fourier transform
nfft = length(y_filt);
res = fft(y_filt,nfft,2)/nfft;
res2 = res(:,1:nfft/2+1); %%%% taking single sided spectrum
res3 = fft(res2,[],2);
for i = 3:1:1500 %%%% dividing each row by first row.
resd(i,:) = res3(i,:)./res3(1,:);
end
I'm assuming that your files are MAT-files, not ASCII. You can do this by having load return a struct and using dynamic field referencing:
n = 4;
for i = 1:n
vname = ['fb20' int2str(i) '0']; % Create file/variable name based on index
s = load(vname); % Load data as struct (overwriting previous s)
x = s.(vname)(3:1:1502,:); % Access struct with dynamic field reference
% Rest of your code
...
end
If you're using a plain ASCII file, load won't produce a struct. However, such files are much simpler (see documentation for load/save). The following code would probably work:
n = 4;
for i = 1:n
vname = ['fb20' int2str(i) '0']; % Create file/variable name based on index
s = load(vname); % Load data as matrix (overwriting previous s)
x = s(3:1:1502,:); % Directly index matrix
% Rest of your code
...
end
It would be a good idea to add the file extension to your load command to make your code more readable.