Including External cpp file in OpenCV cpp Code - c++

I am working on an Image Processing toolbox, that links OpenCV to Scilab, so that OpenCV functions can be used in Scilab directly. Now, my issue is that I have many functions that are used in all the other codes, so i decided to include those in an external cpp file, and include that in my other codes. What I did was, i made a header file common.h with the function definitions. common.c has the actual functions written. And all my other files, for e.g opencv_imcrop have a #include "common.h" along with the other included header files. However, when i compile this in Scilab using my builder gateway file(a .sce file that compiles my opencv_imcrop.cpp), it gives the following error:-
opencv_imcrop.cpp:14:22: fatal error: common.h: No such file or directory
compilation terminated.
This is my common.h file:-
#include "common.cpp"
string type2str(int type);
int no_of_channels(int type);
int retrieveImage(Mat &image);
int returnImage(char *checker,int &temp,Mat img);
This is my common.cpp file:-
string type2str(int type)
{
string r;
uchar depth = type & CV_MAT_DEPTH_MASK;
switch ( depth )
{
case CV_8U: r = "8U"; break;
case CV_8S: r = "8S"; break;
case CV_16U: r = "16U"; break;
case CV_16S: r = "16S"; break;
case CV_32S: r = "32S"; break;
case CV_32F: r = "32F"; break;
case CV_64F: r = "64F"; break;
default: r = "User"; break;
}
return r;
}
int no_of_channels(int type)
{
uchar chans = 1 + (type >> CV_CN_SHIFT);
return chans;
}
//Note : the other 2 functions are also present here, but they
// comprise of 800 lines of code, so i did not paste them here
My opencv_imcrop.cpp(The file that has to include the above made header file to use the functions) file is:-
#include <numeric>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
extern "C"
{
#include "api_scilab.h"
#include "Scierror.h"
#include "BOOL.h"
#include <localization.h>
#include "common.h"
int opencv_imcrop(char *fname, unsigned long fname_len)
{
SciErr sciErr;
int iRows=0,iCols=0;
int *piAddr = NULL;
int *piAddrNew = NULL;
int *piAddr2 = NULL;
int *piAddr3 = NULL;
int *piAddr4 = NULL;
int *piAddr5 = NULL;
unsigned char *pstDataR = NULL;
unsigned char *pstDataG = NULL;
unsigned char *pstDataB = NULL;
int i,j,k;
double *x,*y,*width,*height;
//checking input argument
CheckInputArgument(pvApiCtx, 5, 5);
CheckOutputArgument(pvApiCtx, 1, 1) ;
Mat image;
retrieveImage(image);
//for value of top-left x-coordinate
sciErr = getVarAddressFromPosition(pvApiCtx,2,&piAddr2);
if (sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
sciErr = getMatrixOfDouble(pvApiCtx, piAddr2, &iRows, &iCols ,&x);
if(sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
//for value top-left y-coordinate
sciErr = getVarAddressFromPosition(pvApiCtx,3,&piAddr3);
if (sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
sciErr = getMatrixOfDouble(pvApiCtx, piAddr3, &iRows, &iCols ,&y);
if(sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
//for value of width
sciErr = getVarAddressFromPosition(pvApiCtx,4,&piAddr4);
if (sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
sciErr = getMatrixOfDouble(pvApiCtx, piAddr4, &iRows, &iCols ,&width);
if(sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
//for value of height
sciErr = getVarAddressFromPosition(pvApiCtx,5,&piAddr5);
if (sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
sciErr = getMatrixOfDouble(pvApiCtx, piAddr5, &iRows, &iCols ,&height);
if(sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
//defining a temporary rectangle, that denotes the area that has to be cropped into the new image
Rect myROI(x[0], y[0], width[0], height[0]);
// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
Mat croppedRef(image, myROI);
Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);
int temp = nbInputArgument(pvApiCtx) + 1;
string tempstring = type2str(cropped.type());
char *checker;
checker = (char *)malloc(tempstring.size() + 1);
memcpy(checker, tempstring.c_str(), tempstring.size() + 1);
returnImage(checker,temp,cropped);
//Assigning the list as the Output Variable
AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx) + 1;
//Returning the Output Variables as arguments to the Scilab environment
ReturnArguments(pvApiCtx);
return 0;
}
/* ==================================================================== */
}
And finally, the .sce(builder_gateway_cpp.sce) file i execute in scilab to compile the above cpp file is as follows:-
function builder_gw_cpp()
WITHOUT_AUTO_PUTLHSVAR = %t;
tbx_build_gateway("skeleton_cpp69690", ..
["imcrop","opencv_imcrop"], ..
["opencv_imcrop.cpp"], ..
get_absolute_file_path("builder_gateway_cpp.sce"),[],"g++ -ggdb
`pkg-config --cflags opencv` -o `basename opencv_imcrop.cpp .cpp`
opencv_imcrop.cpp `pkg-config --libs opencv`");
endfunction
builder_gw_cpp();
clear builder_gw_cpp; // remove builder_gw_cpp on stack

Related

How to input sample images in libsvm train code

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,&param);
if(error_msg)
{
fprintf(stderr,"ERROR: %s\n",error_msg);
exit(1);
}
if(cross_validation)
{
do_cross_validation();
}
else
{
model = svm_train(&prob,&param);
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(&param);
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,&param,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".

opencv_NormalizeHist.cpp:47:34: error: 'NormalizeHist' was not declared in this scope

I have written the code to access opencv(Mainly used for image processing) function from Scilab(numerical computation software). When I run bilder gateway file, I am encountering below error.
opencv_NormalizeHist.cpp:47:34: error: 'NormalizeHist' was not declared in this scope.
#include <numeric>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace cv;
using namespace std;
extern "C"
{
#include "api_scilab.h"
#include "Scierror.h"
#include "BOOL.h"
#include <localization.h>
#include "../common.h"
int opencv_NormalizeHist(char *fname, unsigned long fname_len)
{
SciErr sciErr;
int iRows=0,iCols=0;
int *piAddr2 = NULL;
//checking input argument
CheckInputArgument(pvApiCtx, 2, 2);
CheckOutputArgument(pvApiCtx, 0, 0) ;
//Define histogram
Mat hist;
retrieveImage(hist,1);
double *factor;
//for value of factor
sciErr = getVarAddressFromPosition(pvApiCtx,2,&piAddr2);
if (sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
sciErr = getMatrixOfDouble(pvApiCtx, piAddr2, &iRows, &iCols ,&factor);
if(sciErr.iErr)
{
printError(&sciErr, 0);
return 0;
}
NormalizeHist(hist, factor[0]); //Normalizing hist
string tempstring = type2str(hist.type());
char *checker;`enter code herek
checker = (char *)malloc(tempstring.size() + 1);
memcpy(checker, tempstring.c_str(), tempstring.size() + 1);
returnImage(checker,hist,1); //here, remove the temp as a parameter as it is not needed, and instead add 1 as the third parameter. 1 denotes that the first output argument will be this variable
free(checker); //free memory taken up by checker, i missed this earlier
//Assigning the list as the Output Variable
AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx) + 1;
//Returning the Output Variables as arguments to the Scilab environment
ReturnArguments(pvApiCtx);
return 0;
}
/* ==================================================================== */
}

Getting Eclipse's C++ parser to work with Emscripten

I'm having a few problems with Eclipse's C++ parser. I've been using it with Emscripten and found the code completion, call hierarchy, documentation popup, code analysis and related features to be very useful, but it's been bothering me that the parser isn't totally working. Especially with this new problem with using vectors.
The first parsing error is on std::vector<SDL_Rect> box; with the error being:
Symbol 'vector' could not be resolved
And then on emscripten_set_main_loop(game_loop, 60, 1); I get this error:
Function 'usleep' could not be resolved
Here's the full code:
#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include <emscripten.h>
#include <stdarg.h>
#include <libcxx/vector>
///GLOBAL VARIABLES
SDL_Surface* bitmap;
SDL_Surface* screen;
SDL_Rect source;
SDL_Rect destination;
///second sprite
SDL_Surface* bitmap2;
SDL_Rect source2;
SDL_Rect destination2;
/// Side Scrolling variables:
SDL_Rect camera;
SDL_Rect offset;
SDL_Rect offset2;
int level_width = 480 * 5;
int level_height = 640;
bool gameRunning = true;
class buttonpresses {
public:
bool leftButton;
bool rightButton;
bool jumpButton;
};
int movementspeed = 5;
int jumpspeed = 2;
bool jumpenabled = false;
int jumpduration = 0;
int maxjump = 20;
int leftmomentum = 1;
int rightmomentum = 1;
int lastdestination;
int countDestination = 0;
int maxmomentum = 5;
buttonpresses charactermovement;
/// Collision detection
std::vector<SDL_Rect> box;
///MAIN LOOP
void game_loop() {
// EVENT HANDLING
SDL_PumpEvents();
Uint8 *keystate = SDL_GetKeyboardState(NULL);
if (keystate[SDLK_ESCAPE]) {
gameRunning = false;
printf("Game Stopping!!!!!!\n");
SDL_Quit();
exit(0);
}
if (keystate[SDLK_LEFT]) {
// printf("Left Key\n");
charactermovement.leftButton = true;
}
if (keystate[SDLK_LEFT] == false) {
charactermovement.leftButton = false;
}
if (keystate[SDLK_RIGHT]) {
// printf("Right Key\n");
charactermovement.rightButton = true;
}
if (keystate[SDLK_RIGHT] == false) {
charactermovement.rightButton = false;
}
if (keystate[SDLK_SPACE]) {
// printf("Space Key\n");
charactermovement.jumpButton = true;
}
if (keystate[SDLK_SPACE] == false) {
charactermovement.jumpButton = false;
}
// printf("Game Running..\n");
// LOGIC
//character movement
if (charactermovement.rightButton) {
destination.x = destination.x + movementspeed;
}
if (charactermovement.leftButton) {
destination.x = destination.x - movementspeed;
}
if (charactermovement.jumpButton && jumpenabled) {
destination.y = destination.y - jumpspeed;
jumpduration++;
}
destination.x = destination.x + rightmomentum - leftmomentum;
if (destination.y >= 200) {
jumpenabled = true;
// printf ("jump enabled\n");
}
if (jumpduration >= maxjump) {
jumpenabled = false;
}
if (destination.y >= 200) {
// printf ("destination y:");
// printf ("%d\n", destination.y);
jumpduration = 0;
}
//if (jumpenabled != true){
// printf ("jump disabled\n");
//}
//if (jumpenabled == true){
// printf ("jump enabled\n");
// printf ("jump duration: ");
// printf ("%d\n", jumpduration);
//}
//momentum
//save position every 5 interations
if (countDestination > 5) {
lastdestination = destination.x;
countDestination = 0;
} else {
countDestination++;
}
//printf ("last location: ");
//printf ("%d\n", destination.x);
//
//printf ("current location: ");
//printf ("%d\n", lastdestination);
// increase momentum in direction your moving in (relative to previous location)
if (lastdestination > destination.x) {
// printf ("right if running \n ");
if (rightmomentum > 0) {
rightmomentum--;
} else if (leftmomentum < maxmomentum) {
leftmomentum++;
}
}
if (lastdestination < destination.x) {
// printf ("left if running \n ");
if (leftmomentum > 0) {
leftmomentum--;
} else if (rightmomentum < maxmomentum) {
rightmomentum++;
}
}
if (lastdestination == destination.x) {
if (leftmomentum > 0) {
leftmomentum--;
}
if (rightmomentum > 0) {
rightmomentum--;
}
}
printf("left momentum: ");
printf("%d\n", rightmomentum);
printf("right momentum: ");
printf("%d\n", leftmomentum);
//gravity
if (destination.y <= 200) {
destination.y++;
}
offset.x = destination.x - camera.x;
offset2.x = destination2.x - camera.x;
offset.y = destination.y - camera.y;
offset2.y = destination2.y - camera.y;
// RENDERING
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
SDL_BlitSurface(bitmap, &source, screen, &offset);
// RENDER SECOND SPRITE
SDL_BlitSurface(bitmap2, &source2, screen, &offset2);
//blank screen
SDL_Flip(screen);
camera.x++;
}
int main() {
SDL_Init( SDL_INIT_VIDEO);
// LOAD FILES
bitmap = IMG_Load("ninjagaiden3sheet1.png");
screen = SDL_SetVideoMode(640, 480, 0, SDL_HWSURFACE | SDL_DOUBLEBUF);
/// camera variables
camera.x = 0;
camera.y = 0;
camera.w = 640;
camera.h = 480;
/// end camera variables
// Part of the bitmap that we want to draw
source.x = 37;
source.y = 4;
source.w = 17;
source.h = 32;
// Part of the screen we want to draw the sprite to
destination.x = 100;
destination.y = 100;
destination.w = 65;
destination.h = 44;
//// second sprite
bitmap2 = IMG_Load("bat_transparent.png");
source2.x = 24;
source2.y = 63;
source2.w = 65;
source2.h = 44;
destination2.x = 940;
destination2.y = 100;
destination2.w = 65;
destination2.h = 44;
//// end second sprite
lastdestination = destination.x;
offset = destination;
offset2 = destination2;
charactermovement.leftButton = false;
charactermovement.rightButton = false;
charactermovement.jumpButton = false;
//START MAIN LOOP
emscripten_set_main_loop(game_loop, 60, 1);
return 0;
}
My includes tab for C++ in the "Paths and Symbols" properties looks like:
C:\Program Files\Emscripten\emscripten\1.12.0\system\include
C:\Program Files\Emscripten\emscripten\1.12.0\system\include\libc
C:\Program Files\Emscripten\emscripten\1.12.0\system\include\emscripten
C:\Program Files\Emscripten\emscripten\1.12.0\system\include\libcxx
In the Indexer settings I have the following enabled:
Index source files not included in the build
Index unused headers
Index all header variants
Index source and header files opened in editor
Allow heuristic resolution of includes
Skip files larger than: 8 MB
Does anyone know what's going on? Or what I can do to fix it?
Update:
I've fixed the error on parsing std::vector. It turns out that some of llvm/clang libraries use _LIBCPP_BEGIN_NAMESPACE_STD and _LIBCPP_END_NAMESPACE_STD definitions instead of using namespace std; and those defines are invisible to the parser unless __clang__ is defined.
So the solution is to go into the "Symbols" tab for C++ in the "Paths and Symbols" properties and add:
__clang__
In the "Add" dialog that pops up just put it in the Name: input field and press OK. This will also add many of the missing std namespace functions like cout cin etc.
I haven't found a fix for the usleep/emscripten_set_main_loop issue yet but this should be good enough to get the IDE's code completion and several related features to work. Though I'm still having some weird complicated parser issues with Eclipse so I think I'm going to abandon the search for a solution here and work with NetBeans for which I think I have every thing set up.

c++ dynamic allocation with opencv exception

i have the following code. i used it after applying connected components code i have the wanted results from connected components but i'm trying using the following code to remove the very small or very high labels based on a threshold.but every time i debug it i have exception.. so could anybode help me please
this is the connected components code
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
#define PIXEL(img,x,y) (img)->imageData[(x)*img->widthStep+(y)]
#include <iostream>
int main()
{
IplImage *GrayImg,*outImg;
GrayImg=cvLoadImage("Gray_Image.jpg",0);
if(!GrayImg){
printf("Could not load image file: %s\n");
cvWaitKey(0);
exit(0);
}
cvThreshold(GrayImg, GrayImg, 180, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);//converting image to binary
int height,width,channels;
height = GrayImg->height;
width = GrayImg->width;
channels = GrayImg->nChannels;
printf("Processing a %dx%d image with %d channels \n",height,width,channels);
outImg = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
cvZero(outImg);
//cvCopyImage(GrayImg,OutImg);
int i,j,v;
int top,left;
int topL,leftL;
int label=0;
int eq[10000][2];
int eqlength = 1;
cvNamedWindow("Gray", CV_WINDOW_AUTOSIZE);
cvShowImage("Gray", GrayImg );
for (i=0;i<height;i++) {
for (j=0;j<width;j++) {
v = (unsigned char) PIXEL(GrayImg,i,j);// cvGet2D(GrayImg,i,j).val[0];
//unsigned char v1 = PIXEL(GrayImg,i,j);
//int v2 = PIXEL(GrayImg,i,j);
//int v3 = v1;
if (v==255) {
if (i>0) top = cvGet2D(GrayImg,i-1,j).val[0];
else top = 0;
if (j>0) left = cvGet2D(GrayImg,i,j-1).val[0] ;
else left=0;
if (top==0 && left==0)
{
PIXEL(outImg,i,j) = label;
label+=1;
}
else if (top==255 && left==0) {
PIXEL(outImg,i,j) = PIXEL(outImg,i-1,j);
}
else if (top==0 && left==255) {
PIXEL(outImg,i,j) = PIXEL(outImg,i,j-1);
}
else if (top==255 && left==255) {
PIXEL(outImg,i,j) = PIXEL(outImg,i,j-1);
if (PIXEL(outImg,i-1,j) != PIXEL(outImg,i,j-1)){
if (eq[eqlength-1][0] == PIXEL(outImg,i-1,j) && eq[eqlength-1][1] == PIXEL(outImg,i,j-1)) ;
else
{
eq[eqlength][0] = PIXEL(outImg,i-1,j);
eq[eqlength][1] = PIXEL(outImg,i,j-1);
eqlength++;
}
}
}
}
}
//cvWaitKey(0);
//cvShowImage("Out", outImg);
}
int e;
for (i=0;i<height;i++)
for (j=0;j<width;j++)
if (PIXEL(outImg,i,j)!=0)
for (e=1;e<eqlength;e++)
if (PIXEL(outImg,i,j)==eq[e][0])
PIXEL(outImg,i,j)=eq[e][1];
cvNamedWindow("Out", CV_WINDOW_AUTOSIZE);
cvShowImage("Out", outImg);
and this is the code i added to remove unwanted labels
int* arr = new int [N];
//cout<<endl<<arr[0];
for (i=0;i<height;i++)
{
for (j=0;j<width;j++)
{
id=(unsigned char)PIXEL(outImg,i,j);
arr[id]++;
}
}
for (i=0;i<=N;i++)
{
if (arr[i]<5 || arr[i]>50)
arr[i]=0;
}
for (i=0;i<outImg->height;i++)
{
for (j=0;j<outImg->width;j++)
{
id=(unsigned char)PIXEL(outImg,i,j);
//id=cvGet2D(outImg,i,j).val[0];
if (arr[id]==0)
PIXEL(outImg,i,j)=0;
else
PIXEL(outImg,i,j)=255;
}
}
delete [] arr;
cvNamedWindow("CC", CV_WINDOW_AUTOSIZE);
cvShowImage("CC", outImg);
cvWaitKey(0);
/* Free memory and get out */
cvDestroyWindow("Gray");
cvReleaseImage(&GrayImg);
return 0;
}
You are exceeding the bounds of your array arr. Indexes are 0 based in C++ so when allocating an array of size N your maximum index is N-1.
int* arr = new int [N];
...
for (i=0;i<=N;i++) // Accessing element N of arr which does not exist. Use '<'
{
if (arr[i]<5 || arr[i]>50)
arr[i]=0;
}

C++/SDL loading array of strings from lua

I'm using lua to load my maps in C++/SDL and i have an array in lua that determines the location of the tile image but I don't know how to transfer it to an array in C++ I've looked for an explanation but they all deal with ints and the lua files only have 1 array and for some reason the code doesn't work this is probably a stupid question but yeah
Here is the code:
Map.lua
Tile = {}
--opens file and reads it
local file = io.open("../Maps/Map.txt")
local n = 0
while(n <= 494) do
Tile[n] = file:read(1)
n = n+1
end
file:close()
--end of reading file
n = 0
local x = 0
-- creates a new array for the tiles
whatsTile = {}
isSolid = {}
--sets the tiles to their specific image
while(n <= 494) do
if(Tile[n] ~= "\n" and Tile[n] ~= "\r") then
if(Tile[n] == '0') then
--This is the array in lua that holds the file location
whatsTile[x] = "../GameResources/Pictures/Tile1.bmp"
--sets this tile to non solid
isSolid[x] = 0
end
--You can add new tiles just set their number and, add a directory for the Bitmap image.
--Make sure you set the directory based on where the executable file is, not this script.
x = x+1
end
n = n+1
end
main.cpp
#include <SDL/SDL.h>
#include <string>
#include <iostream>
#include <lua.hpp>
#include <fstream>
using namespace std;
extern "C"{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <luaconf.h>
}
void loadMapLua();
//This is the array i want to transfer the values into
string whatsTile[475];
int main(int argc, char** argv){
ofstream myfile;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Event event;
loadMapLua();
SDL_Surface* Screen = SDL_SetVideoMode(800, 608, 32, SDL_SWSURFACE);
SDL_Surface* BackGround = SDL_LoadBMP("../GameResources/Pictures/BackGround.bmp");
SDL_Surface* Tiles[475];
const char* c;
SDL_Rect Tile[475];
int n = 0;
while(n < 475){
c = whatsTile[n].c_str();
Tiles[n] = SDL_LoadBMP(c);
Tile[n].w = 32;
Tile[n].h = 32;
Tile[n].x = n*32;
Tile[n].y = (n/25)*32;
n ++;
}
n = 0;
myfile.open("trolls.txt");
myfile << whatsTile[0] << endl;
myfile.close();
bool gameRunning = true;
while(gameRunning){
while(SDL_PollEvent(&event)){
if(event.type == SDL_QUIT){
gameRunning = false;
}
}
SDL_FillRect(Screen, 0, SDL_MapRGB(Screen->format, 255, 255, 255));
SDL_BlitSurface(BackGround, NULL, Screen, NULL);
while(n < 475){
SDL_BlitSurface(Tiles[n], NULL, Screen, &Tile[n]);
n ++;
}
SDL_Flip(Screen);
}
SDL_Quit();
return 0;
}
void loadMapLua(){
lua_State* Map = lua_open();
luaL_openlibs(Map);
luaL_dofile(Map, "../GameResources/LuaScripts/Map.lua");
lua_pushnil(Map);
lua_close(Map);
}
You cannot get whole array at once.
Use looping to get all the strings.
string whatsTile[475];
int len_whatsTile = 0;
void loadMapLua(){
lua_State* L = lua_open();
luaL_openlibs(L);
luaL_dofile(L, "../GameResources/LuaScripts/Map.lua");
lua_getglobal(L, "whatsTile");
int Index = 0;
do {
lua_pushinteger(L, Index++);
lua_gettable(L, -2);
if (lua_isnil(L, -1))
Index = 0;
else
whatsTile[len_whatsTile++].assign(lua_tostring(L, -1));
lua_pop(L, 1);
} while (Index > 0);
lua_close(L);
}