I have downloaded the libsvm code for object detection. I am having problems in using the train svm code. I can't input the sample files properly. Anyone please help me how to input positive and negative images.Here is the train code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "svm.h"
#define Malloc(type,n) (type *)malloc((n)*sizeof(type))
void print_null(const char *s) {}
void exit_with_help()
{
printf(
"Usage: svm-train [options] training_set_file [model_file]\n"
"options:\n"
"-s svm_type : set type of SVM (default 0)\n"
" 0 -- C-SVC (multi-class classification)\n"
" 1 -- nu-SVC (multi-class classification)\n"
" 2 -- one-class SVM\n"
" 3 -- epsilon-SVR (regression)\n"
" 4 -- nu-SVR (regression)\n"
"-t kernel_type : set type of kernel function (default 2)\n"
" 0 -- linear: u'*v\n"
" 1 -- polynomial: (gamma*u'*v + coef0)^degree\n"
" 2 -- radial basis function: exp(-gamma*|u-v|^2)\n"
" 3 -- sigmoid: tanh(gamma*u'*v + coef0)\n"
" 4 -- precomputed kernel (kernel values in training_set_file)\n"
"-d degree : set degree in kernel function (default 3)\n"
"-g gamma : set gamma in kernel function (default 1/num_features)\n"
"-r coef0 : set coef0 in kernel function (default 0)\n"
"-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)\n"
"-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)\n"
"-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)\n"
"-m cachesize : set cache memory size in MB (default 100)\n"
"-e epsilon : set tolerance of termination criterion (default 0.001)\n"
"-h shrinking : whether to use the shrinking heuristics, 0 or 1 (default 1)\n"
"-b probability_estimates : whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)\n"
"-wi weight : set the parameter C of class i to weight*C, for C-SVC (default 1)\n"
"-v n: n-fold cross validation mode\n"
"-q : quiet mode (no outputs)\n"
);
exit(1);
}
void exit_input_error(int line_num)
{
fprintf(stderr,"Wrong input format at line %d\n", line_num);
exit(1);
}
void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name);
void read_problem(const char *filename);
void do_cross_validation();
struct svm_parameter param; // set by parse_command_line
struct svm_problem prob; // set by read_problem
struct svm_model *model;
struct svm_node *x_space;
int cross_validation;
int nr_fold;
static char *line = NULL;
static int max_line_len;
static char* readline(FILE *input)
{
int len;
if(fgets(line,max_line_len,input) == NULL)
return NULL;
while(strrchr(line,'\n') == NULL)
{
max_line_len *= 2;
line = (char *) realloc(line,max_line_len);
len = (int) strlen(line);
if(fgets(line+len,max_line_len-len,input) == NULL)
break;
}
return line;
}
int main(int argc, char **argv)
{
char input_file_name[1024];
char model_file_name[1024];
const char *error_msg;
parse_command_line(argc, argv, input_file_name, model_file_name);
read_problem(input_file_name);
error_msg = svm_check_parameter(&prob,¶m);
if(error_msg)
{
fprintf(stderr,"ERROR: %s\n",error_msg);
exit(1);
}
if(cross_validation)
{
do_cross_validation();
}
else
{
model = svm_train(&prob,¶m);
if(svm_save_model(model_file_name,model))
{
fprintf(stderr, "can't save model to file %s\n", model_file_name);
exit(1);
}
svm_free_and_destroy_model(&model);
}
svm_destroy_param(¶m);
free(prob.y);
free(prob.x);
free(x_space);
free(line);
return 0;
}
void do_cross_validation()
{
int i;
int total_correct = 0;
double total_error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
double *target = Malloc(double,prob.l);
svm_cross_validation(&prob,¶m,nr_fold,target);
if(param.svm_type == EPSILON_SVR ||
param.svm_type == NU_SVR)
{
for(i=0;i<prob.l;i++)
{
double y = prob.y[i];
double v = target[i];
total_error += (v-y)*(v-y);
sumv += v;
sumy += y;
sumvv += v*v;
sumyy += y*y;
sumvy += v*y;
}
printf("Cross Validation Mean squared error = %g\n",total_error/prob.l);
printf("Cross Validation Squared correlation coefficient = %g\n",
((prob.l*sumvy-sumv*sumy)*(prob.l*sumvy-sumv*sumy))/
((prob.l*sumvv-sumv*sumv)*(prob.l*sumyy-sumy*sumy))
);
}
else
{
for(i=0;i<prob.l;i++)
if(target[i] == prob.y[i])
++total_correct;
printf("Cross Validation Accuracy = %g%%\n",100.0*total_correct/prob.l);
}
free(target);
}
void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name)
{
int i;
void (*print_func)(const char*) = NULL; // default printing to stdout
// default values
param.svm_type = C_SVC;
param.kernel_type = RBF;
param.degree = 3;
param.gamma = 0; // 1/num_features
param.coef0 = 0;
param.nu = 0.5;
param.cache_size = 100;
param.C = 1;
param.eps = 1e-3;
param.p = 0.1;
param.shrinking = 1;
param.probability = 0;
param.nr_weight = 0;
param.weight_label = NULL;
param.weight = NULL;
cross_validation = 0;
// parse options
for(i=1;i<argc;i++)
{
if(argv[i][0] != '-') break;
if(++i>=argc)
exit_with_help();
switch(argv[i-1][1])
{
case 's':
param.svm_type = atoi(argv[i]);
break;
case 't':
param.kernel_type = atoi(argv[i]);
break;
case 'd':
param.degree = atoi(argv[i]);
break;
case 'g':
param.gamma = atof(argv[i]);
break;
case 'r':
param.coef0 = atof(argv[i]);
break;
case 'n':
param.nu = atof(argv[i]);
break;
case 'm':
param.cache_size = atof(argv[i]);
break;
case 'c':
param.C = atof(argv[i]);
break;
case 'e':
param.eps = atof(argv[i]);
break;
case 'p':
param.p = atof(argv[i]);
break;
case 'h':
param.shrinking = atoi(argv[i]);
break;
case 'b':
param.probability = atoi(argv[i]);
break;
case 'q':
print_func = &print_null;
i--;
break;
case 'v':
cross_validation = 1;
nr_fold = atoi(argv[i]);
if(nr_fold < 2)
{
fprintf(stderr,"n-fold cross validation: n must >= 2\n");
exit_with_help();
}
break;
case 'w':
++param.nr_weight;
param.weight_label = (int *)realloc(param.weight_label,sizeof(int)*param.nr_weight);
param.weight = (double *)realloc(param.weight,sizeof(double)*param.nr_weight);
param.weight_label[param.nr_weight-1] = atoi(&argv[i-1][2]);
param.weight[param.nr_weight-1] = atof(argv[i]);
break;
default:
fprintf(stderr,"Unknown option: -%c\n", argv[i-1][1]);
exit_with_help();
}
}
svm_set_print_string_function(print_func);
// determine filenames
if(i>=argc)
exit_with_help();
strcpy(input_file_name, argv[i]);
if(i<argc-1)
strcpy(model_file_name,argv[i+1]);
else
{
char *p = strrchr(argv[i],'/');
if(p==NULL)
p = argv[i];
else
++p;
sprintf(model_file_name,"%s.model",p);
}
}
// read in a problem (in svmlight format)
void read_problem(const char *filename)
{
int max_index, inst_max_index, i;
size_t elements, j;
FILE *fp = fopen(filename,"r");
char *endptr;
char *idx, *val, *label;
if(fp == NULL)
{
fprintf(stderr,"can't open input file %s\n",filename);
exit(1);
}
prob.l = 0;
elements = 0;
max_line_len = 1024;
line = Malloc(char,max_line_len);
while(readline(fp)!=NULL)
{
char *p = strtok(line," \t"); // label
// features
while(1)
{
p = strtok(NULL," \t");
if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
break;
++elements;
}
++elements;
++prob.l;
}
rewind(fp);
prob.y = Malloc(double,prob.l);
prob.x = Malloc(struct svm_node *,prob.l);
x_space = Malloc(struct svm_node,elements);
max_index = 0;
j=0;
for(i=0;i<prob.l;i++)
{
inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
readline(fp);
prob.x[i] = &x_space[j];
label = strtok(line," \t\n");
if(label == NULL) // empty line
exit_input_error(i+1);
prob.y[i] = strtod(label,&endptr);
if(endptr == label || *endptr != '\0')
exit_input_error(i+1);
while(1)
{
idx = strtok(NULL,":");
val = strtok(NULL," \t");
if(val == NULL)
break;
errno = 0;
x_space[j].index = (int) strtol(idx,&endptr,10);
if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
exit_input_error(i+1);
else
inst_max_index = x_space[j].index;
errno = 0;
x_space[j].value = strtod(val,&endptr);
if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
exit_input_error(i+1);
++j;
}
if(inst_max_index > max_index)
max_index = inst_max_index;
x_space[j++].index = -1;
}
if(param.gamma == 0 && max_index > 0)
param.gamma = 1.0/max_index;
if(param.kernel_type == PRECOMPUTED)
for(i=0;i<prob.l;i++)
{
if (prob.x[i][0].index != 0)
{
fprintf(stderr,"Wrong input format: first column must be 0:sample_serial_number\n");
exit(1);
}
if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)
{
fprintf(stderr,"Wrong input format: sample_serial_number out of range\n");
exit(1);
}
}
fclose(fp);
}
UPDATE
can i convert to numerical representation using this code?
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cv.h>
#include <highgui.h>
#include <cvaux.h>
#include <iostream>
#include <vector>
#include<string.h>
using namespace std;
using namespace cv;
int main ( int argc, char** argv )
{
cout << "OpenCV Training SVM Automatic Number Plate Recognition\n";
cout << "\n";
char* path_Plates;
char* path_NoPlates;
int numPlates;
int numNoPlates;
int imageWidth=150;
int imageHeight=150;
//Check if user specify image to process
if(1)
{
numPlates= 12;
numNoPlates= 67 ;
path_Plates= "/home/kaushik/opencv_work/Manas6/Pics/Positive_Images/";
path_NoPlates= "/home/kaushik/opencv_work/Manas6/Pics/Negative_Images/i";
}else{
cout << "Usage:\n" << argv[0] << " <num Plate Files> <num Non Plate Files> <path to plate folder files> <path to non plate files> \n";
return 0;
}
Mat classes;//(numPlates+numNoPlates, 1, CV_32FC1);
Mat trainingData;//(numPlates+numNoPlates, imageWidth*imageHeight, CV_32FC1 );
Mat trainingImages;
vector<int> trainingLabels;
for(int i=1; i<= numPlates; i++)
{
stringstream ss(stringstream::in | stringstream::out);
ss<<path_Plates<<i<<".jpg";
try{
const char* a = ss.str().c_str();
printf("\n%s\n",a);
Mat img = imread(ss.str(), CV_LOAD_IMAGE_UNCHANGED);
img= img.clone().reshape(1, 1);
//imshow("Window",img);
//cout<<ss.str();
trainingImages.push_back(img);
trainingLabels.push_back(1);
}
catch(Exception e){;}
}
for(int i=0; i< numNoPlates; i++)
{
stringstream ss(stringstream::in | stringstream::out);
ss << path_NoPlates<<i << ".jpg";
try
{
const char* a = ss.str().c_str();
printf("\n%s\n",a);
Mat img=imread(ss.str(),CV_LOAD_IMAGE_UNCHANGED);
//imshow("Win",img);
img= img.clone().reshape(1, 1);
trainingImages.push_back(img);
trainingLabels.push_back(0);
//cout<<ss.str();
}
catch(Exception e){;}
}
Mat(trainingImages).copyTo(trainingData);
//trainingData = trainingData.reshape(1,trainingData.rows);
trainingData.convertTo(trainingData, CV_32FC1);
Mat(trainingLabels).copyTo(classes);
FileStorage fs("SVM.xml", FileStorage::WRITE);
fs << "TrainingData" << trainingData;
fs << "classes" << classes;
fs.release();
return 0;
}
What I can see from your code is, that you are mixing OpenCV and LIBSVM.
Basically you can follow one of the following ways. Personally I would suggest to use OpenCV only.
OpenCV
OpenCV is a very powerfull library for working with images. Hence they implement their own machine learning algorithms including SVMs.
As described in a very good way here it is very easy to perform classification with images via OpenCV since the algorithms use a common interface for this purpose.
LIBSVM
LIBSVM a standalone library for SVM classification in various form (e.g. multiclass, two-class, with probability estimates, etc). If you go this way, you have to perform the following steps in order to do successful classification:
Think about how many different classes you want to differentiate (e.g. + / -)
Maybe preprocess your images (filters, ...)
Extract so called "features" rom your images using a feature selection method (for example: Mutual Information). Those methods will tell you, which points are significant for your given classes since we follow the basic assumption, that not every singel pixel in an image is important.
According to your extracted features you transform your images to an vectorial representation.
Write it into an file according to the LIBSVM data format:
label feature_id1:feature_value1 feature_id2:feature_value2
+1 1:0.53265 2:0.5232
-1 1:0.78543 2:0.64326
Proceed with "svm_train" according to its description. Classification would be a combination of 2.) 4.) 5.) and a run of "svm_predict".
Related
I am using LittleFS library and ESP32 on arduino IDE.
I am reading a file using the example readFile function of LittleFS but I am trying to convert it for my needs.
The text written to the file is of this form:
LettersAndNumbersMax30&LettersAndNumbersMax30&00&00&01&01
Seperated by &. 2 text values of max 30 characters and 4 integers.
I want to build:
char *mytest1 containing the first text
char *mytest2 containing the second text
int mytest3 containing the first integer (2digits)
int mytest4 containing the second integer (2digits)
int mytest5 containing the third integer (2digits)
int mytest5 containing the forth integer (2digits)
file.read() returns and integer always. for example 38 for &.
void readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
while(file.available()){
Serial.write(file.read());
}
file.close();
}
Its fairly straightforward. Test each byte read and act accordingly. Code below doesn't handle signs nor negative numbers. It also doesn't check if there are only digits for integers in the file.
#include ....
struct record_t
{
char myState1[31];
char myState2[31];
int myState3;
int myState4;
int myState5;
int myState6;
};
record_t record;
bool readFile(fs::FS &fs, const char * path);
void setup()
{
// ...
}
void loop()
{
//...
if (readFile(/*...*/))
{
Serial.printf("file reads OK\r\n");
//...
}
}
bool readFile(fs::FS &fs, const char * path)
{
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if (!file || file.isDirectory())
{
Serial.println("- failed to open file for reading");
return;
}
Serial.println("- read from file:");
int state = 0;
int index = 0;
// clear record.
record.myState1[0] = 0;
record.myState2[0] = 0;
record.myState3 = 0;
record.myState4 = 0;
record.myState5 = 0;
record.myState6 = 0;
bool valid = false;
for (int i = file.read(); i != -1; i = file.read())
{
char c = i & 0xFF;
Serial.write(c); // file.read() returns an int, that's why Serial.write()
// was printing numbers.
switch(state)
{
case 0:
if (index > sizeof(record.myState1) - 1) // avoid buffer overflow
index = sizeof(record.myState1) - 1;
if (c != '&')
{
record.myState1[index++] = c;
}
else
{
record.myState1[index] = 0;
++state;
index = 0;
}
break;
case 1:
if (index > sizeof(record.myState2) - 1) // avoid buffer overflow
index = sizeof(record.myState2) - 1;
if (c != '&')
{
record.myState2[index++] = c;
}
else
{
record.myState2[index] = 0;
++state;
index = 0;
}
break;
case 2:
if (c != '&')
record.myState3 = record.myState3 * 10 + (c - '0');
else
++state;
break;
case 3:
if (c != '&')
record.myState4 = record.myState4 * 10 + (c - '0');
else
++state;
break;
case 4:
if (c != '&')
record.myState5 = record.myState5 * 10 + (c - '0');
else
++state;
break;
case 5:
valid = true;
if (c != '&')
record.myState6 = record.myState6 * 10 + (c - '0');
else
++state;
break;
default: // reaching here is an error condition? You decide.
return false;
}
}
file.close();
if (!valid)
{
// clear record.
record.myState1[0] = 0;
record.myState2[0] = 0;
record.myState3 = 0;
record.myState4 = 0;
record.myState5 = 0;
record.myState6 = 0;
}
return valid;
}
file.read returns integer. So the integer is printed.
You to convert it to the string.
while(file.available()){
char s[2] = {0};
s[0] = file.read();
Serial.write(s);
}
I thought it would be a good best practice to search thru my code for any references like ..
char buf[MAX_STRING_LENGTH];
... and replace them with ...
char buf[MAX_STRING_LENGTH] = {'\0'};
Doing a search in the code I have a number that are set to null (around 239) and others that are not (1,116).
When I replaced the remaining 1,116 instances with char buf[MAX_STRING_LENGTH] = {'\0'}; and pushed the code live the game was noticeably laggy.
Reverting the change removed the lag.
Can someone explain why setting these to null would cause the game to lag while running?
Example code setting to Null
void do_olist(Character *ch, char *argument, int cmd)
{
int header = 1;
int type = -1;
int wear_bit = -1;
int i = 0;
int inclusive;
int zone = -1;
int yes_key1 = 0;
int yes_key2 = 0;
int yes_key3 = 0;
int count = 0;
Object *obj;
bool found = false;
char key1 [MAX_STRING_LENGTH] = {'\0'};
char key2 [MAX_STRING_LENGTH] = {'\0'};
char key3 [MAX_STRING_LENGTH] = {'\0'};
char buf [MAX_STRING_LENGTH];
argument = one_argument(argument, buf);
if (!*buf)
{
ch->send("Selection Parameters:\n\n");
ch->send(" +/-<object keyword> Include/exclude object keyword.\n");
ch->send(" <zone> Objects from zone only.\n");
ch->send(" <item-type> Include items of item-type.\n");
ch->send(" <wear-bits> Include items of wear type.\n");
ch->send("\nExample: olist +sword -rusty weapon 10\n");
ch->send("will only get non-rusty swords of type weapon from zone 10.\n");
return;
}
while (*buf)
{
inclusive = 1;
if (strlen(buf) > 1 && isalpha(*buf) &&
(type = index_lookup(item_types, buf)) != -1)
{
argument = one_argument(argument, buf);
continue;
}
if (strlen(buf) > 1 && isalpha(*buf) &&
(wear_bit = index_lookup(wear_bits, buf)) != -1)
{
argument = one_argument(argument, buf);
continue;
}
if (isdigit(*buf))
{
if ((zone = atoi(buf)) >= MAX_ZONE)
{
ch->send("Zone not in range 0..99\n");
return;
}
argument = one_argument(argument, buf);
continue;
}
switch (*buf)
{
case '-':
inclusive = 0;
case '+':
if (!buf [1])
{
ch->send("Expected keyname after 'k'.\n");
return;
}
if (!*key1)
{
yes_key1 = inclusive;
strcpy(key1, buf + 1);
}
else if (!*key2)
{
yes_key2 = inclusive;
strcpy(key2, buf + 1);
}
else if (*key3)
{
ch->send("Sorry, at most three keywords.\n");
return;
}
else
{
yes_key3 = inclusive;
strcpy(key3, buf + 1);
}
break;
case 'z':
argument = one_argument(argument, buf);
if (!isdigit(*buf) || atoi(buf) >= MAX_ZONE)
{
ch->send("Expected valid zone after 'z'.\n");
return;
}
zone = atoi(buf);
break;
}
argument = one_argument(argument, buf);
}
*b_buf = '\0';
for (obj = full_object_list; obj; obj = obj->lnext)
{
if (zone != -1 && obj->zone != zone)
continue;
if (type != -1 && obj->obj_flags.type_flag != type)
continue;
if (wear_bit != -1)
{
for (i = 0; (*wear_bits[i] != '\n'); i++)
{
if (IS_SET(obj->obj_flags.wear_flags, (1 << i)))
{
if (i != wear_bit)
continue;
else
found = true;
}
}
if (found)
found = false;
else
continue;
}
if (*key1)
{
if (yes_key1 && !strcasestr(const_cast<char*> (obj->getName().c_str()), key1))
continue;
else if (!yes_key1 && strcasestr(const_cast<char*> (obj->getName().c_str()), key1))
continue;
}
if (*key2)
{
if (yes_key2 && !strcasestr(const_cast<char*> (obj->getName().c_str()), key2))
continue;
else if (!yes_key2 && strcasestr(const_cast<char*> (obj->getName().c_str()), key2))
continue;
}
if (*key3)
{
if (yes_key3 && !strcasestr(const_cast<char*> (obj->getName().c_str()), key3))
continue;
else if (!yes_key3 && strcasestr(const_cast<char*> (obj->getName().c_str()), key3))
continue;
}
count++;
if (count < 200)
olist_show(obj, type, header);
header = 0;
}
if (count > 200)
{
sprintf(buf, "You have selected %d objects (too many to print all at once).\n",
count);
ch->send(buf);
//return;
}
else {
sprintf(buf, "You have selected %d objects.\n",
count);
ch->send(buf);
}
page_string(ch->desc, b_buf);
}
I took the advice to replace instances of ...
char buf[MAX_STRING_LENGTH] = {'\0'};
with ...
char buf[MAX_STRING_LENGTH]; *buf = 0;
I'm doing a quick binary tree program as a homework, but I am getting weird errors that I can't seem to figure out how to fix. Normally I'm programming in C#, and C is just slightly different but different enough for me to get confused.
Here is the code that is giving the error:
void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;
do {
flag = 1;
for (int i = 0; i < arraySize - 1; i++)
{
if (stubList[i].b > stubList[i + 1].b) {
Swap(stubList[i], stubList[i + 1]);
flag = 0;
}
}
} while (flag == 0);
printf("Sorted by value of variable 'b'"); _getch(); _getch();
}
And here is the whole script:
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct stub
{
char crown[51];//some custom name - can be empty
float b;//comparable value for tree sort
int c;//limited by maxint
stub *l;//left node(normally smaller "b" value than this node)
stub *r;//right node(normally bigger "b" value than this node)
};
stub *stubList[255];//empty list of a stub array with a safe casual amount
int arraySize = 0;
stub *head = NULL;//main stub(first)
stub *latest = NULL;//latest stub
stub *st = NULL;//used for creating and checking
FILE *fs = NULL;
char fileName[255];
int maxint = 20;//for var 'c'
void BTreeNodeToArray(stub *s) {
stubList[arraySize] = s;
arraySize++;
}
void Swap(stub &s1, stub &s2) {
stub temp = s2;
s1 = s2;
s2 = temp;
}
int MaxMin(int num) {
int clampedInt = num;
if (num < 0) clampedInt = 0;
else if (num > maxint) clampedInt = maxint;
return clampedInt;
}
//Create a completely new stub with crown, b, and c variables being filled here
void CreateElement() {
st = new stub;
printf("Adding information for node:\n");
printf("Node name: "); gets_s(st->crown);
printf("\n");
float f;
printf("Node float value (B): "); scanf_s("%f", &f);
st->b = f;
printf("\n");
int d;
printf("Node integer value (C): "); scanf_s("%d", &d);
st->c = d;
printf("\n");
st->c = MaxMin(st->c);
st->l = NULL;
st->r = NULL;
}
//creates the very first stub(root/head)
void CreateFirst() {
printf("First in tree. Adding root node...\n");
CreateElement();
head = st;
latest = head;
BTreeNodeToArray(head);
printf("Added head stub\ncrown: %s\nValue: %f\nExtra: %d", head->crown, head->b, head->c);
getchar();
getchar();
}
void AddStub() {
if (head == NULL) {
CreateFirst();
}
else {
CreateElement();//create newest node
latest = st;
st = head;
int depth = 0;
while (1) {
if ((latest->b <= st->b)) {//choose left if true
printf("Went left\n");
depth++;
if (st->l == NULL) {//node free, assign here
printf("Node assigned at depth %d\n", depth);
st->l = latest;
BTreeNodeToArray(latest);
getchar();
getchar();
break;
}
else {//loop again with next node
//printf("New loop (left)\n");
st = st->l;
}
}
else {//choose right
printf("Went right\n");
depth++;
if (st->r == NULL) {//node free, assign here
printf("Node assigned at depth %d\n", depth);
st->r = latest;
BTreeNodeToArray(latest);
getchar();
getchar();
break;
}
else {//loop again with next node
//printf("New loop (right)\n");
st = st->r;
}
}
}
}
}
void ViewArray() {
for (int i = 0; i < arraySize; i++)
{
printf_s("Node [%d]:\n\tCrown: %s\n\tweight: %f\n\tExta value(0 - %d): %d\n", i, stubList[i]->crown, stubList[i]->b, maxint, stubList[i]->c);
}
getchar();
}
void SortArray() {//bubble sorting by float value of 'b'
int flag = 0;
do {
flag = 1;
for (int i = 0; i < arraySize - 1; i++)
{
if (stubList[i].b > stubList[i + 1].b) {
Swap(stubList[i], stubList[i + 1]);
flag = 0;
}
}
} while (flag == 0);
printf("Sorted by value of variable 'b'"); _getch(); _getch();
}
void ProcessArray() {
char c = ' ';
int found = 0;
printf("Process with character: \n"); c = _getch();
if (arraySize <= 0) {
printf("No List!");
return;
}
char chkstr[5];
for (short i = 0; i < 5; i++)//simple assign to a 'string' 5 times
{
chkstr[i] = c;
}
for (int i = 0; i < arraySize; i++)
{
if (strstr(stubList[i]->crown, chkstr) != NULL) {
// contains
printf("B = %f at [%d] \n", stubList[i]->b, i);
found++;
}
}
if (found > 0) {
printf("---Found: %d with character %c---", found, c);
}
else {
printf("No elements found with '%c'", c);
}
getchar();
}
void ExportArray() {
FILE *fs = NULL;
char fileName[255];
errno_t err;
printf("Save to file as: \n"); gets_s(fileName);
if (strlen(fileName) == 0) {
printf("Failed to create file. File name empty!");
_getch();
_getch();
}
err = fopen_s(&fs, fileName, "wb");
if (err != 0) {
printf("Failed to create file!!!");
_getch();
_getch();
return;
}
for (int i = 0; i < arraySize; i++)
{
int written = fwrite(&stubList[i], sizeof(stub), 1, fs);
//fwrite(&gr[i], sizeof(student), 1, fs);
}
int numclosed = _fcloseall();
printf("Exported to file: %s", fileName);
getchar();
}
void CleanReset() {//reset all values and release memory (function used for import)
for (int i = 0; i < arraySize; i++)
{
delete stubList[i];
}
arraySize = 0;
st = NULL;
head = NULL;
latest = NULL;
}
void ImportArray() {
FILE *fs = NULL;
char fname[255];
errno_t err;
printf("Open FIle: "); gets_s(fname);
err = fopen_s(&fs, fname, "rb");
if (err == 0) {
CleanReset();
fseek(fs, 0, SEEK_END);
long size = ftell(fs);
arraySize = size / sizeof(stub);//get amount of students saved
fseek(fs, 0, SEEK_SET);
int i = 0;
st = new stub;
fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
stubList[i] = st;
while (!feof(fs)) {
i++;
st = new stub;
fread_s(&st, sizeof(stub), sizeof(stub), 1, fs);
stubList[i] = st;
}
printf("File data imported. Size: %d", arraySize);
getchar();
return;
}
printf("Failed to import file!!!");
getchar();
}
void main()
{
system("chcp 65001");//use utf8
char izb = 'i';
while (izb != '0') {
system("cls");
printf_s("1. Add stub\n");
printf_s("2. View Array\n");
printf_s("3. Sort Array\n");
printf_s("4. Process\n");
printf_s("5. Export array to file\n");
printf_s("6. Import array from file\n");
printf_s("0. Exit\n\n");
printf_s("Choose action:\n"); izb = _getch();
switch (izb)
{
case '1':
AddStub();
break;
case '2':
ViewArray();
break;
case '3':
SortArray();
break;
case '4':
ProcessArray();
break;
case '5':
ExportArray();
break;
case '6':
ImportArray();
break;
case '0':
//Exit();
break;
}
}
}
The error is that you want to pass a stub * to a function that wants a stub &. The first one is a pointer, the second one is a reference.
You have two options.
First option (imho recommended):
Change your swap function to accept pointers instead of references.
void Swap(stub *s1, stub *s2) {
stub temp = *s2;
*s1 = *s2;
*s2 = temp;
}
Second option:
Dereference the parameters before passing to swap:
Swap(*(stubList[i]), *(stubList[i + 1]));
You have to undestand that the datatype in your list is a pointer to stub, the function Swap wants a reference, which are different things in C++.
For a better understanding I recommend reading this: https://www.geeksforgeeks.org/pointers-vs-references-cpp/
I am trying to detect the drive letter in Windows. Drive is a primary drive in second IDE channel. I am using GetLogicalDrives().
But this does not tell me I am accessing IDE primary drive.
Here is an example:
#include <cstdint>
#include <windows.h>
#include <cstdio>
const char* GetTypeOfDrive(const char* Drive)
{
const char* Result = NULL;
unsigned int DriveType = GetDriveType(Drive);
switch(DriveType)
{
case DRIVE_FIXED:
Result = "Hard disk";
break;
case DRIVE_CDROM:
Result = "CD/DVD";
break;
case DRIVE_REMOVABLE:
Result = "Removable";
break;
case DRIVE_REMOTE:
Result = "Network";
break;
default:
Result = "Unknown";
break;
}
return Result;
}
int GetLogicalDrivesList(char Drives[26])
{
int Res = 0;
DWORD DrivesMask = GetLogicalDrives();
for (int I = 0; I < 26; ++I)
{
if (DrivesMask & (1 << I))
{
Drives[Res++] = 'A' + I;
}
}
return Res;
}
int main()
{
char temp[4];
char drives[26];
int drive_count = GetLogicalDrivesList(drives);
for (int i = 0; i < drive_count; ++i)
{
sprintf(temp, "%c:/", drives[i]);
printf("%c is a %s\n", drives[i], GetTypeOfDrive(temp));
}
}
I have noted that the cascades trained with the program opencv_traincascade does not run with the current version of opencv_performance. I've tried to convert the old performance cpp file to load the new types of cascades, but without success. The code is here:
#include "cv.h"
#include "highgui.h"
#include <cstdio>
#include <cmath>
#include <ctime>
#include <math.h>
#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#ifndef PATH_MAX
#define PATH_MAX 512
#endif /* PATH_MAX */
/*typedef struct HidCascade {
int size;
int count;
} HidCascade;
*/
typedef struct ObjectPos {
float x;
float y;
float width;
int found; /* for reference */
int neghbors;
} ObjectPos;
using namespace std;
using namespace cv;
int main(int argc, char* argv[]) {
int i, j;
char* classifierdir = NULL;
//char* samplesdir = NULL;
int saveDetected = 1;
double scale_factor = 1.1;
float maxSizeDiff = 1.5F;
float maxPosDiff = 1.1F;
/* number of stages. if <=0 all stages are used */
//int nos = -1, nos0;
int width = 25;
int height = 15;
int rocsize;
FILE* info;
FILE* resultados;
char* infoname;
char fullname[PATH_MAX];
//char detfilename[PATH_MAX];
char* filename;
//char detname[] = "det-";
CascadeClassifier cascade;
double totaltime;
if (!(resultados = fopen("resultados.txt", "w"))) {
printf("Cannot create results file.\n");
exit(-1);
}
infoname = (char*) "";
rocsize = 20;
if (argc == 1) {
printf("Usage: %s\n -data <classifier_directory_name>\n"
" -info <collection_file_name>\n"
" [-maxSizeDiff <max_size_difference = %f>]\n"
" [-maxPosDiff <max_position_difference = %f>]\n"
" [-sf <scale_factor = %f>]\n"
" [-ni]\n"
" [-rs <roc_size = %d>]\n"
" [-w <sample_width = %d>]\n"
" [-h <sample_height = %d>]\n", argv[0], maxSizeDiff,
maxPosDiff, scale_factor, rocsize, width, height);
return 0;
}
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-data")) {
classifierdir = argv[++i];
} else if (!strcmp(argv[i], "-info")) {
infoname = argv[++i];
} else if (!strcmp(argv[i], "-maxSizeDiff")) {
maxSizeDiff = (float) atof(argv[++i]);
} else if (!strcmp(argv[i], "-maxPosDiff")) {
maxPosDiff = (float) atof(argv[++i]);
} else if (!strcmp(argv[i], "-sf")) {
scale_factor = atof(argv[++i]);
} else if (!strcmp(argv[i], "-ni")) {
saveDetected = 0;
} else if (!strcmp(argv[i], "-rs")) {
rocsize = atoi(argv[++i]);
} else if (!strcmp(argv[i], "-w")) {
width = atoi(argv[++i]);
} else if (!strcmp(argv[i], "-h")) {
height = atoi(argv[++i]);
}
}
if (!cascade.load(classifierdir)) {
printf("Unable to load classifier from %s\n", classifierdir);
return 1;
}
strcpy(fullname, infoname);
filename = strrchr(fullname, '\\');
if (filename == NULL) {
filename = strrchr(fullname, '/');
}
if (filename == NULL) {
filename = fullname;
} else {
filename++;
}
info = fopen(infoname, "r");
totaltime = 0.0;
if (info != NULL) {
int x, y, width, height;
Mat img;
int hits, missed, falseAlarms;
int totalHits, totalMissed, totalFalseAlarms;
int found;
float distance;
int refcount;
ObjectPos* ref;
int detcount;
ObjectPos* det;
int error = 0;
int* pos;
int* neg;
pos = (int*) cvAlloc(rocsize * sizeof(*pos));
neg = (int*) cvAlloc(rocsize * sizeof(*neg));
for (i = 0; i < rocsize; i++) {
pos[i] = neg[i] = 0;
}
printf("+================================+======+======+======+\n");
printf("| File Name | Hits |Missed| False|\n");
printf("+================================+======+======+======+\n");
fprintf(resultados,
"+================================+======+======+======+\n");
fprintf(resultados,
"| File Name | Hits |Missed| False|\n");
fprintf(resultados,
"+================================+======+======+======+\n");
//fprintf (resultados, "%d\n",framesCnt);
totalHits = totalMissed = totalFalseAlarms = 0;
while (!feof(info)) {
fscanf(info, "%s %d", filename, &refcount);
img = imread(fullname);
if (!img.data) {
cout << "ow" << endl;
return -1;
}
ref = (ObjectPos*) cvAlloc(refcount * sizeof(*ref));
for (i = 0; i < refcount; i++) {
error = (fscanf(info, "%d %d %d %d", &x, &y, &width, &height)
!= 4);
if (error)
break;
ref[i].x = 0.5F * width + x;
ref[i].y = 0.5F * height + y;
ref[i].width = sqrt(0.5F * (width * width + height * height));
ref[i].found = 0;
ref[i].neghbors = 0; //in the new cascade, where to get the neighbors?
}
vector<Rect> obj_detectados;
Rect retang;
if (!error) {
totaltime -= time(0);
cascade.detectMultiScale(img, obj_detectados, scale_factor, 4, 0
//|CV_HAAR_FIND_BIGGEST_OBJECT
// |CV_HAAR_DO_ROUGH_SEARCH
| CV_HAAR_SCALE_IMAGE, Size(25, 15));
totaltime += time(0);
if (obj_detectados.size() == 0) {
detcount = 0;
} else {
detcount = obj_detectados.size();
}
det = (detcount > 0) ?
((ObjectPos*) cvAlloc(detcount * sizeof(*det))) : NULL;
hits = missed = falseAlarms = 0;
for (vector<Rect>::const_iterator r = obj_detectados.begin();
r != obj_detectados.end(); r++, i++) {
Point r1, r2;
r1.x = (r->x);
r1.y = (r->y);
r2.x = (r->x + r->width);
r2.y = (r->y + r->height);
retang.x = r1.x;
retang.y = r1.y;
retang.width = abs(r2.x - r1.x);
retang.height = abs(r2.y - r1.y);
if (saveDetected) {
rectangle(img, retang, Scalar(0, 0, 255), 3, CV_AA);
}
det[i].x = 0.5F*r->width + r->x;
det[i].y = 0.5F*r->height + r->y;
det[i].width = sqrt(0.5F * (r->width * r->width
+ r->height * r->height));
det[i].neghbors = 1; // i don't know if it will work...
// det[i].neghbors = r.neighbors; --- how to do it in the new version??
found = 0;
for (j = 0; j < refcount; j++) {
distance = sqrtf( (det[i].x - ref[j].x) * (det[i].x - ref[j].x) +
(det[i].y - ref[j].y) * (det[i].y - ref[j].y) );
//cout << distance << endl;
if( (distance < ref[j].width * maxPosDiff) &&
(det[i].width > ref[j].width / maxSizeDiff) &&
(det[i].width < ref[j].width * maxSizeDiff) )
{
ref[j].found = 1;
ref[j].neghbors = MAX( ref[j].neghbors, det[i].neghbors );
found = 1;
}
}
if (!found) {
falseAlarms++;
neg[MIN(det[i].neghbors, rocsize - 1)]++;
//neg[MIN(0, rocsize - 1)]++;
}
}
//imshow("teste", img);
if (saveDetected) {
//strcpy(detfilename, detname);
//strcat(detfilename, filename);
//strcpy(filename, detfilename);
imwrite(fullname, img);
//cvvSaveImage(fullname, img);
}
for (j = 0; j < refcount; j++) {
if (ref[j].found) {
hits++;
//pos[MIN(0, rocsize - 1)]++;
pos[MIN(ref[j].neghbors, rocsize - 1)]++;
} else {
missed++;
}
}
totalHits += hits;
totalMissed += missed;
totalFalseAlarms += falseAlarms;
printf("|%32.64s|%6d|%6d|%6d|\n", filename, hits, missed,
falseAlarms);
//printf("+--------------------------------+------+------+------+\n");
fprintf(resultados, "|%32.64s|%6d|%6d|%6d|\n", filename, hits,
missed, falseAlarms);
//fprintf(resultados,
// "+--------------------------------+------+------+------+\n");
fflush(stdout);
if (det) {
cvFree( &det);
det = NULL;
}
} /* if( !error ) */
//char c = (char) waitKey(10);
// if (c == 27)
// exit(0);
cvFree( &ref);
}
fclose(info);
printf("|%32.32s|%6d|%6d|%6d|\n", "Total", totalHits, totalMissed,
totalFalseAlarms);
fprintf(resultados, "|%32.32s|%6d|%6d|%6d|\n", "Total", totalHits,
totalMissed, totalFalseAlarms);
printf("+================================+======+======+======+\n");
fprintf(resultados,
"+================================+======+======+======+\n");
//printf("Number of stages: %d\n", nos);
//printf("Number of weak classifiers: %d\n", numclassifiers[nos - 1]);
printf("Total time: %f\n", totaltime);
fprintf(resultados, "Total time: %f\n", totaltime);
/* print ROC to stdout */
for (i = rocsize - 1; i > 0; i--) {
pos[i - 1] += pos[i];
neg[i - 1] += neg[i];
}
//fprintf(stderr, "%d\n", nos);
for (i = 0; i < rocsize; i++) {
fprintf(stderr, "\t%d\t%d\t%f\t%f\n", pos[i], neg[i],
((float) pos[i]) / (totalHits + totalMissed),
((float) neg[i]) / (totalHits + totalMissed));
}
cvFree( &pos);
cvFree( &neg);
}
return 0;
}
My doubt is about the det[i].neghbors = r.neighbors; in the old performance.cpp. How I retrieve the neighbors in this new version?
Anyone could help me to convert opencv_performance to run the new cascades from opencv_traincascade?
Many thanks!