OpenCV training to detect static image - opencv

I want to detect the flag of my country. But I have trouble with training. I have one positive sample and 4 negative samples. This is my folder structrue:
/negative
/img
img1.jpg
img2.jpg
img3.jpg
img4.jpg
/positive
flag.jpg
This is how I call create_samples:
opencv_createsamples -img positive/flag.jpg -vec flag.vec
But command does not finish and popup windows appears saying that error appeared. This is output of create_samples command:
Info file name: (NULL)
Img file name: positive/flag.jpg
Vec file name: flag.vec
BG file name: (NULL)
Num: 1000
BG color: 0
BG threshold: 80
Invert: FALSE
Max intensity deviation: 40
Max x angle: 1.1
Max y angle: 1.1
Max z angle: 0.5
Show samples: FALSE
Width: 24
Height: 24
Create training samples from single image applying distortions...
Can anyone guide me through the process of haar training of static image (1 image) in OpenCV? I am running Windows 7 Ultimate x64
EDIT
This works:
opencv_createsamples -img positive/flag.jpg -vec flag.vec -num 0
I guess the problem is with -num 0 parameter

Haar is not your best shot at detecting a country's flag , better use color detection
COLOR_MIN = np.array([20, 80, 80],np.uint8)
COLOR_MAX = np.array([40, 255, 255],np.uint8)
but if you still insist on haar
creating samples :
$ <opencv_createsamples> -vec <binary_description> -image <positive_image> -bg <negative_description>
Training the cascade :
$ <opencv_traincascade> -data <cascade> -vec <binary_description> -bg <negative_description>

Related

Weka RF doesn't give any confusion matrix or expected results

I am using WEKA to classify a small dataset with only 27 instances into a binary classification. I have tried with bigger datasets and weka show the confusion matrix and the other metrics, but with my main and small 27 instances dataset only shows this:
Scheme: weka.classifiers.trees.RandomForest -P 100 -I 100 -num-slots 1 -K 0 -M 1.0 -V 0.001 -S 1
Relation: t_PROMIS_mtbi-weka.filters.unsupervised.attribute.Remove-R1
Instances: 27
Attributes: 7
Var2
Var3
Var4
Var5
Var6
Var7
ERS
Test mode: 10-fold cross-validation
=== Classifier model (full training set) ===
RandomForest
Bagging with 100 iterations and base learner
weka.classifiers.trees.RandomTree -K 0 -M 1.0 -V 0.001 -S 1 -do-not-check-capabilities
Time taken to build model: 0.01 seconds
=== Cross-validation ===
=== Summary ===
Correlation coefficient 0.0348
Mean absolute error 0.4544
Root mean squared error 0.529
Relative absolute error 91.7269 %
Root relative squared error 102.952 %
Total Number of Instances 27
i don't undersantd why this is happening. Is it a size thing?
I have already solved it, The problem was that i was using numbers 1/0 on my class viariable, I changed it for a "Yes"/"No" variable and works.

What modifications can I make in svmtrain of LIBSVM to improve the accuracy of my spam classifier?

I am using Octave version 5.2.0 and LIBSVM 3.24 to build a spam classifier.
Without using LIBSVM I got an accuracy of >99% on both test and train data.
But while using LIBSVM, I only get an accuracy of 68-69% .What modifications should I do on my LIBSVM options?
This is the code I used
model = svmtrain(X, y,'-c 0.1 -t 2 -s 0 -g 1000');
p = svmpredict(y,X,model);
Are you aware of the settings of LibSVM?
% libSVM options:
% -s svm_type: set type of SVM (default 0)
% 0 -- C-SVC
% 1 -- nu-SVC
% 2 -- one-class SVM
% 3 -- epsilon-SVR
% 4 -- nu-SVR
% -t kernel_type: set type of kernel function (default 2)
% 0 -- linear: u'*v
% 1 -- polynomial: (gamma*u'*v + coef0)^degree
% 2 -- radial basis function: exp(-gamma*|u-v|^2)
% 3 -- sigmoid: tanh(gamma*u'*v + coef0)
% -d degree: set degree in kernel function (default 3)
% -g gamma: set gamma in kernel function (default 1/num_features)
% -r coef0: set coef0 in kernel function (default 0)
% -c cost: set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
% -n nu: set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
% -p epsilon: set the epsilon in loss function of epsilon-SVR (default 0.1)
% -m cachesize: set cache memory size in MB (default 100)
% -e epsilon: set tolerance of termination criterion (default 0.001)
% -h shrinking: whether to use the shrinking heuristics, 0 or 1 (default 1)
% -b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
% -wi weight: set the parameter C of class i to weight*C, for C-SVC (default 1)
So your -s 0 -t 2 -g 1000 -c 0.1 settings translate to a C-SVM (-s 0) with a Gaussian kernel (-t 2) with a large scaling (-g 1000) and a smaller than default cost for violations (-c 0.1).
I suggest to try it first with the default values (-s 0 -t 2), and than increase the cost -c. Your gamma looks ridiculously large but without knowing your data, none can judge this. Have a look on hyperparameter optimization, which exactly sets those values. There exists plenty of work on this but I am only familiar with regression analysis. If in doubt, do a global optimization on those parameters through gridsearch or ga.

opencv_createsamples "Assertion Failed" Error

I am trying to create a vec file from my positive image samples. I'm using the latest version of Opencv. The command I am using is this:
opencv_createsamples -info Positive.info -num 3750 -w 24 -h 24 -vec Positive.vec
All my images are bigger than 24x24, so I don't believe that that is the issue. I've tried searching online, but I don't find anyone with this error while doing the createsamples command. The output that I get when I run that is this:
Info file name: Positive.info
Img file name: (NULL)
Vec file name: Positive.vec
BG file name: (NULL)
Num: 3750
BG color: 0
BG threshold: 80
Invert: FALSE
Max intensity deviation: 40
Max x angle: 1.1
Max y angle: 1.1
Max z angle: 0.5
Show samples: FALSE
Width: 24
Height: 24
Max Scale: -1
RNG Seed: 12345
Create training samples from images collection...
OpenCV: terminate handler is called! The last OpenCV error is:
OpenCV(4.0.0-alpha) Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in cv::Mat::Mat, file c:\build\master_winpack-build-win64-vc15\opencv\modules\core\src\matrix.cpp, line 465
This is my first time using opencv, so I'm very unclear as to what this error is. Anyone have any experience with this or can point me in the right direction to correcting the error?
This is Priyanka.
I was also getting the same error and I was trying to get resolution to it somehow.
But I could not find anything on internet.
But I am able to solve the problem successfully.
2-3 things that were missing as below:
I used opencv_annotation.exe to generate the -info (text file). This utility embeds complete image path into the file, where as the opencv_createsamples.exe expects that the images are present in the same folder as of the -info file. So what used to happen was the path of the image was getting concatenated with the path of the -info file.
i.e Suppose -info file is available at D:\MyPath\DataSet\annotations.txt and the images are at D:\MyPath\DataSet\Vehicles\*.png. In this case, while executing the opencv_createsamples.exe, the complete image path becomes D:\MyPath\DataSet\D:\MyPath\DataSet\Vehicles\image000.png, which the utility is not able to find.
So cater to the correct path kindly take care of below things
put the -info file in the same path as of images.
ensure that the -info file does not have the path for any image. It should contain only the
<image name without complete path> <object instances> <x y, width height>
With this change the image path was taken correctly and my issue got resolved.
Try doing this. It may help you.
This is Tushar Pathade, this error comes when your info.txt(file which contains information of objects to be detected) file contains some wrong information like image_name 1 0 0 0 0 or image_name 2 10 20 30 40. In first examples coordinates are (0,0,0,0) which is impossible while in second example no. of objects are 2 but coordinates of only one objects are mentioned.
So this lines produced this error. So first remove it and then run. You will not get any error then.
As priyanka mentioned above, this also need to take care of first but this will produced another error. It is nothing but image not found error. So to avoid it put info.txt file in a folder where negative images are. Basically u will see path in error so accordingly handle it.
Thank you.
I got the same error.
The error is about the bounding boxes, sometimes while creating bounding boxes you create a box outside the image pixel so that region is not get accepted and then you get this error.
Solution :
I used divide and conquer tech for this solution. What I did is I've created a new text file and in that text file I pasted some files from the original info or text file I ran the code if its creating samples then good if not then delete any one image from that text file run again*(run the create_samples again)*. do this until you get the clean file. I know this is too tedious task but this works.!
Thanks
I face the same issue now, if the num argument is less than 950 it works for me.

OpenCV createsamples - invalid background description file

I'm in my OPENCV_ROOT folder and running the following command in Win-x64:
opencv_createsamples -bgcolor 0 -bgthresh 0 -maxxangle 1.1 -maxyangle 1.1
maxzangle 0.5 -maxidev 40 -w 80 -h 40
-img ABSOLUTE_PATH_TO_POSITIVE_IMAGES_FOLDER\car.jpg
-bg ABSOLUTE_PATH_TO_PROJECT\negatives.txt
-vec ABSOLUTE_PATH_TO_SAMPLES_FOLDER\car.jpg.vec
-num 125
My negatives.txt looks like this:
negative_images\city01_02.jpg
negative_images\city01_04.jpg
negative_images\city01_05.jpg
negative_images\city01_06.jpg
negative_images\city01_07.jpg
This is my output:
Info file name: (NULL)
Img file name: ABSOLUTE_PATH_TO_POSITIVE_IMAGES_FOLDER\car.jpg
Vec file name: ABSOLUTE_PATH_TO_SAMPLES_FOLDER\car.jpg.vec
BG file name: ABSOLUTE_PATH_TO_PROJECT\negatives.txt
Num: 125
BG color: 0
BG threshold: 0
Invert: FALSE
Max intensity deviation: 40
Max x angle: 1.1
Max y angle: 1.1
Max z angle: 0.5
Show samples: FALSE
Width: 80
Height: 40
Create training samples from single image applying distortions...
Invalid background description file.
What's invalid about my negatives collection file (negatives.txt)? I tried listing the files within it both with absolute paths and with relative paths. I'm following this tutorial.
If you created the file on Windows, and running it on Linux e.g. Ubuntu, you have to change the "End of line sequence".
Click on the bottom of the editor on CR LF and change it to LF and try again!
Notepad++:
Visual Studio Code:
Geany: Documents > Set Line Endings > Convert and Set to LF (Unix)
Problem solved! The issue was simply that I had written the collection file names in Notepad++, and it all seemed fine. But when I happened to open the same file in notepad, I noticed there were no newlines after each image filename! When I added the newlines, and ran the command, the samples got created without errors!
I had the same problem. Just skip lines between addresses of the images. For example: before my negatives.dat file was:
./Negative_Images/197.
./Negative_Images/69.
./Negative_Images/510.
./Negative_Images/513.
./Negative_Images/169.png
Now it's:
./Negative_Images/197.png
./Negative_Images/69.png
./Negative_Images/510.png
./Negative_Images/513.png
./Negative_Images/169.png
Problem solved.
In my case, I was creating this bg.txt file with a script. Basically, it was doing :
for (int i = 0; i < numberOfImages; i++)
{
myDescFile << imagesFolder + std::to_string(i) + ".jpg\n";
}
I simply added another \n and the problem went away!
myDescFile << imagesFolder + std::to_string(i) + ".jpg\n\n";
EDIT:
You also have to make sure that your paths have/or\\ as separators. Else, you will be able to run the opencv_createsamples.exe cmd, won't have error, but will never see the Done at the end.
ex:L:/imgTraining/plant/bnw/0.jpg
Here's a picture of a good bg file from notepad++ (With View>Show Symbol>Show End of Line activated and Edit>EOL Conversion>Windows (CR LF) selected):
Install dos2unix on Linux by sudo apt-get install dos2unix.
And now you just need to use dos2unix YourFileName.txt.

Haartraining opencv

I am tryng to train cascades using haar training.I have used the following parameters.
C:\opencv\opencv_bin\bin>opencv_haartraining -data haar -vec train.vec -bg neg.
txt -numPos 1000 -numNeg 2000 -nstages 10 -mem 2000 -mode all -w 30 -h 32
but i am getting the following error
Data dir name: haar
Vec file name: train.vec
BG file name: neg.txt, is a vecfile: no
Num pos: 2000
Num neg: 2000
Num stages: 10
Num splits: 1 (stump as weak classifier)
Mem: 2000 MB
Symmetric: TRUE
Min hit rate: 0.995000
Max false alarm rate: 0.500000
Weight trimming: 0.950000
Equal weights: FALSE
Mode: BASIC
Width: 30
Height: 32
Applied boosting algorithm: GAB
Error (valid only for Discrete and Real AdaBoost): misclass
Max number of splits in tree cascade: 0
Min number of positive samples per cluster: 500
Required leaf false alarm rate: 0.000976563
Tree Classifier
Stage
+---+
| 0|
+---+
Number of features used : 234720
Parent node: NULL
*** 1 cluster ***
OpenCV Error: Unspecified error (Vec file sample size mismatch) in icvGetHaarTra
iningDataFromVec, file C:\Downloads\Software\OpenCV-2.2.0-win\OpenCV-2.2.0\modul
es\haartraining\cvhaartraining.cpp, line 1929
terminate called after throwing an instance of 'cv::Exception'
what(): C:\Downloads\Software\OpenCV-2.2.0-win\OpenCV-2.2.0\modules\haartrain
ing\cvhaartraining.cpp:1929: error: (-2) Vec file sample size mismatch in functi
on icvGetHaarTrainingDataFromVec
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
C:\opencv\opencv_bin\bin>cmd |as.txt
'as.txt' is not recognized as an internal or external command,
operable program or batch file.
i am using a vec file having 1000 samples which i downloaded from the internet,and have 2000 negative samples.
"Vec file sample size mismatch" - Try checking the site for the size of the samples. The vec file may not be the one for 30x32 images(which you are trying to pass as -w 30 -h 32).
This is just a guess. Try it. And try using traincascade object. It is there in $OpencvDir$/apps/traincascade/. Compile it like any other object. It can be used for LBP and HOG as well.
Hope this helps.
Regards,
Prasanna S
The ratio of w and h is different from the setting in info.txt. You should modify w's and h's of all images in info.txt int 30:32.

Resources