re-formuling the question, I have this code that reads the names of 2500 files in a folder and then read them one by one and extract specific information from them to write that info in new files, the problem is that after extracting the info of exactly 533 files it doesnt open the next ones, the extrae function tells me by logs that the files cant be opened, but i make sure that every time a file has opened i close it after i extract this info i need, so i dont know why it doesnt allow me to read the files after the 533 files read,help plz
this is my function that extract the info
enter code here
std::vector<Cliente> Extraccion::extrae(std::string path, std::vector<Journal> conjunto, std::vector<BanderaEnvio> envios, std::vector<CFD> cfd, std::vector<TIM> tim, std::vector<CentroReparto> lista, std::vector<DomiciliacionS702> domis, std::vector<CargosEnAclaracion> cargos, std::vector<CaracImpresion> impresion)
{
std::vector<Cliente> clientesF;
std::vector<Encabezado> encabezados;
clientesF.clear();
encabezados.clear();
Cliente *nuevoCliente = new Cliente();
int i = 0;
std::string bin = "";
int r =0;
int countCli=0;
long tmaline;
bool bwrite = true;
std::string canal = "";
std::string msglog = "";
int ctesOmitidos = 0;
int openFile = 0;
std::string linea = "";
std::fstream file;
std::cout<<"---Extrae el Archivo "<<path<<std::endl;
file.open(path.c_str(), ios::in);
if (file.good())
{
// //std::cout<<"____________________entra a leer archivo______________________"<<std::endl<<std::endl;
while(!file.eof())
{
/*lee la longitud de la linea */
std::getline(file,linea);
i++;
// std::cout<<"LINEA "<<i<<std::endl;
tmaline = linea.length();
canal = linea.substr(0, 3);
/*Metemos la Cabecera(canales con HD al inicio), donde viene el num de cliente y su producto */
if(linea.substr(0, 2) == "HD")
{
Encabezado cab(linea.substr(3,6),util.trim(linea.substr(66,30)));//new Encabezado(linea.substr(3,6),util.trim(linea.substr(66,30))); //.util.trim()
encabezados.push_back(cab);
// //std::cout<<"AQUI ESTA EL PRODUCTO : "<<cab.getProducto()<<std::endl;
// //std::cout<<util.trim(linea.substr(66,30)); //cab.producto;
}
else
{
//cout<<"---------no hay encabezados---------"<<std::endl<<std::endl;
if (canal == "BH1")
{
//case 1/*"BH1"*/:
if(nuevoCliente->strCliente.numCta != "0")
{
if (bwrite == true)
{
if(nuevoCliente->strCliente.saldoEPP=="")
nuevoCliente->strCliente.saldoEPP="[0.00]";
if(nuevoCliente->strCliente.saldoPromCompr=="")
nuevoCliente->strCliente.saldoPromCompr="0.00";
if(nuevoCliente->strCliente.saldoPromDispo=="")
nuevoCliente->strCliente.saldoPromDispo="0.00";
if(nuevoCliente->strCliente.saldoProm=="")
nuevoCliente->strCliente.saldoProm="0.00";
if(nuevoCliente->strCliente.saldoPromDispMax=="")
nuevoCliente->strCliente.saldoPromDispMax="0.00";
clientesF.push_back(*nuevoCliente);
}
else
{
// //std::cout<<"Falso para: "<<nuevoCliente->strCliente.numCta<<"|"<<nuevoCliente->strCliente.numtargta<<std::endl;
countCli--;
ctesOmitidos++;
}
nuevoCliente = new Cliente();
nuevoCliente->strCliente.numCta = "0";
msglog = "";
bwrite = true;
//nuevoCliente = new Cliente();
}
if(tmaline >= 1308)
{
++countCli;
nuevoCliente->strCliente.numCta = linea.substr(9,19); //NUMERO DE CUENTA
nuevoCliente->strCliente.numCliente = linea.substr(47,19); //NUMERO DE CLIENTE
bin=linea.substr(12, 6);
nuevoCliente->strCliente.jobOrigen = getProdJob(getNombreENTR(path),encabezados[0].getProducto().substr(0, 8)); //.get(0).getProducto().substr(0,8));
nuevoCliente->strCliente.numCta = linea.substr(9,19); //NUMERO DE CUENTA
nuevoCliente->strCliente.numtargta = linea.substr(28,19);
nuevoCliente->strCliente.domiciliacion = getDomiciliacion(domis, nuevoCliente->strCliente.numtargta); //DOMICILIACION
nuevoCliente->strCliente.cargosEnAclaracion=getCargo(cargos, nuevoCliente->strCliente.numCta+nuevoCliente->strCliente.numtargta); //CARGOS ACLARACION
nuevoCliente->strCliente.numCliente = linea.substr(47,19); //NUMERO DE CLIENTE
nuevoCliente->strCliente.numContra = " "; //NUMERO DE CONTRATO
nuevoCliente->strCliente.bandEnvio = linea.substr(867,1); //BANDERA ENVIO
nuevoCliente->strCliente.codBar = getCodigoBarras(conjunto,linea.substr(28,19)); //NUMERO DE TARJETA regresa CODIGO BARRAS
nuevoCliente->strCliente.medEnvio = getBandEnvio(envios,linea.substr(867,1)); //BANDERA regresa MEDIO ENVIO
nuevoCliente->strCliente.numProd = linea.substr(3,6);
nuevoCliente->strCliente.nomProd = getProducto(encabezados,linea.substr(3,6)); //NUM PRODUCTO regresa NOMBRE PRODUCTO
nuevoCliente->strCliente.fechaAper = completaFechaAp(linea.substr(981,6)); //FECHA APERTURA
nuevoCliente->strCliente.saldoActCorte = convierteCifras(linea.substr(206,12)); //SALDO ACTUAL AL CORTE
nuevoCliente->strCliente.saldoTotalCorte = convierteCifras(linea.substr(1296,12));//SALDO TOTAL AL CORTE
nuevoCliente->strCliente.mesesVencidos = linea.substr(739,1); //MESES VENCIDOS
nuevoCliente->strCliente.fechaLimite = completaFechaAp(linea.substr(230,6)); //FECHA LIMITE
nuevoCliente->strCliente.fechaCorte = completaFechaAp(linea.substr(224,6)); //FECHA CORTE
nuevoCliente->strCliente.fechaCorteArch = encabezados[0].getProducto().substr(0,4)+encabezados[0].getProducto().substr(6,2);//"FECHA";//getFechaArch(path); //FECHA CORTE ARCHIVO
nuevoCliente->strCliente.nombre = util.trim(linea.substr(486,40));//.util.trim(); //NOMBRE
nuevoCliente->strCliente.cp = util.trim(linea.substr(726,12));//.util.trim(); //CODIGO POSTAL
nuevoCliente->strCliente.cr = getCentroReparto(lista, nuevoCliente->strCliente.cp);
nuevoCliente->strCliente.dir1 = util.trim(linea.substr(526,40));//.util.trim(); //{
nuevoCliente->strCliente.dir2 = util.trim(linea.substr(566,40));//.util.trim();
nuevoCliente->strCliente.dir3 = util.trim(linea.substr(606,40));//.util.trim(); //DIRECCION
nuevoCliente->strCliente.dir4 = util.trim(linea.substr(646,40));//.util.trim();
nuevoCliente->strCliente.dir5 = util.trim(linea.substr(686,40));//.util.trim(); //}
nuevoCliente->strCliente.altBlockCode = linea.substr(869,1); //ALT BLOCK CODE
nuevoCliente->strCliente.blockCode = linea.substr(868,1); //BLOCK CODE
nuevoCliente->strCliente.uuID =getUId(cfd, tim,nuevoCliente->strCliente.numCta.substr(3,16)); //UUID
nuevoCliente->strCliente.tipo = isNuevo(nuevoCliente->strCliente.fechaAper, nuevoCliente->strCliente.fechaCorte, 30);
}
else
{
if (tmaline >= 66)
{
nuevoCliente->strCliente.numCliente = linea.substr(47,19);
nuevoCliente->strCliente.numCta = linea.substr(9,19);
}else
{
nuevoCliente->strCliente.numCliente = "No Identificado";
nuevoCliente->strCliente.numCta = "XX";
}
bwrite = false;
msglog = msglog + "Canal BH1 Linea " + std::to_string(i)+"; ";
}
} /*Fin if Canal BH1*/
else if (canal == "BH2")
{
/*Lectura Canal BH2*/
if (tmaline >= 781)
{
std::string plan = linea.substr(79,5); //PLAN
int p = atoi(plan.c_str());//integer.parseInt(plan);
if(p>=90000 && p<=91200)
{ // [90000,91200]
std::string saldo = convierteCifras(linea.substr(769,12));
nuevoCliente->strCliente.saldoEPP+="["+saldo+"]";
//cout<<" BH2 saldoEPP: "<<nuevoCliente->strCliente.saldoEPP <<" Cliente :"<<nuevoCliente->strCliente.numCliente<<std::endl;
}
}
else
{
bwrite = false;
msglog = msglog + "Canal BH2 Linea " + std::to_string(i) + "; ";
}
}/*Fin if Canal BH2*/
else if(canal == "BH6")
{
if (tmaline >= 453)
{
nuevoCliente->strCliente.plasticID=linea.substr(148,3);
nuevoCliente->strCliente.disenoImpresion=dameDisenoImpresion(impresion, linea.substr(148,3)+" "+bin);
nuevoCliente->strCliente.tipoImpresion=dameTipoImpresion(impresion, linea.substr(148,3)+" "+bin);
std::string rfc = isRfcValido(linea.substr(440,13)); //RFC
//string rfc;
nuevoCliente->strCliente.tipoPer = rfc.substr(0, 2);
nuevoCliente->strCliente.rfcFinal = rfc.substr(2, (rfc.length()-2));
if(nuevoCliente->strCliente.tipoPer == ("PI"))
{
nuevoCliente->strCliente.tipoPer ="RFC INCORRECTO";
}
}
else
{
bwrite = false;
msglog = msglog + "Canal BH6 Linea " + std::to_string(i) + "; ";
}
}/*Fin if Canal BH6*/
else if (canal == "BHV")
{
if( tmaline >= 318 ){
if(linea.substr(101,12) !="00000000000 ")
nuevoCliente->strCliente.saldoPromCompr = convierteCifras(linea.substr(101,12));
if(linea.substr(306,12)!="00000000000 ")
nuevoCliente->strCliente.saldoPromDispo = convierteCifras(linea.substr(306,12));
if(linea.substr(227,12)!="00000000000 ")
nuevoCliente->strCliente.saldoProm = convierteCifras(linea.substr(227,12));
if(linea.substr(164,12)!="00000000000 ")
nuevoCliente->strCliente.saldoPromDispMax = convierteCifras(linea.substr(164,12));
}
else{
bwrite = false;
msglog = msglog + "Canal BHV Linea " + std::to_string(i) + "; ";
}
}/*Fin if Canal BHV*/
}/*FIN DEL ELSE AL HD*/
}/*FIN DEL CICLO*/
file.close();
}/*FIN DEL IF OPEN*/
else
{
std::cout<<"ERROR!!! el archivo "<<path<<" no se pudo crear"<<std::endl;
}
delete(nuevoCliente);
std::cout<<"sale del extrae"<<std::endl;
// file.close();
return clientesF;
}/*FIN DEL EXTRAE*/
And in the main i have a for each loop that calls the extraction function for every single file read
enter code here
int main(int argc, char** args)
{
time_t now = time(0);
tm *ltm = gmtime(&now);
std::string shini = std::to_string(ltm->tm_hour)+":"+std::to_string(ltm->tm_min)+":"+std::to_string(ltm->tm_sec);
std::ofstream archivo;
archivo.open("/desarrollo/pruebasc++/pruebasJuan/Salida/tiempos.txt");
archivo<<shini<<std::endl;
/*----------------------------------------------------------------------------------------------------------------------------------------------------------------------*/
//comienza la prueba
Extraccion ex = {};
ManejaArchivos archivos{};
std::vector<Cliente> todosClientes;
std::vector<BanderaEnvio> banderasEnvio;
std::vector<CFD> CFDS;
std::vector<TIM> TIMS;
std::vector<CentroReparto> centrosReparto;
std::vector<DomiciliacionS702> domicilios;
std::vector<CargosEnAclaracion> cargos;
std::vector<CaracImpresion> impresiones;
std::vector<Journal> journals;
banderasEnvio.clear();
centrosReparto.clear();
impresiones.clear();
std::string pathENTR = "";
std::string pathJOUR = "";
int ppba = 1; /*1- Usa la ruta de Producción; 2- Usa nuestra ruta de prueba*/
if (ppba == 1)
{
pathENTR = "/NAS01/01.Ingenieria_NFS/08_Agosto";//args[0];//C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916";
pathJOUR = "/user1/BANAMEX/Salida_doc1/TDC_L6_ECS/08_Agosto";//args[1];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/jour";
}
else
{
pathENTR = "/desarrollo/pruebasc++/pruebasJuan/ENTR";//args[0];//C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916";
pathJOUR = "/desarrollo/pruebasc++/pruebasJuan/JOURNAL";//args[1];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/jour";
}
std::string pathMedioEnvio = "/NAS01/01.Ingenieria_NFS/08_Agosto/Medio_envio_Flag.TXT";//args[2];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/otros/Medio_envio_Flag.TXT";
std::string pathSalida = "/desarrollo/pruebasc++/pruebasJuan/Salida";//args[3];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/Salida";
std::string pathCentrRep = "/NAS01/01.Ingenieria_NFS/08_Agosto/catalogo_sepomex.txt";//args[4];//"C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/otros/catalogo_sepomex.txt";
std::string pathImpresion = "/NAS01/01.Ingenieria_NFS/08_Agosto/ControlBanderas.txt";//args[5];//C:/Users/efmartinezg/Desktop/IsaacDATAMART_030916/otros/ControlBanderas.txt";
double pesoENTR = 0;
double pesoDOM = 0;
double pesoDISP = 0;
double pesoTIM = 0;
double pesoCFD = 0;
double pesoJOUR = 0;
double sumaPesos = 0;
double tiempo = 0;
std::vector<std::string> jours;
std::vector<std::string> entrs = archivos.getENTRS(pathENTR);
archivo<<"Nombres de archivos"<<std::endl;
int contadorIteraciones = 0;
if (entrs.size() >= 1 )
{
std::cout<<"Lee los Catalogos Medio_envio_Flag, BanderaEnvio y CaracImpresion"<<std::endl;
banderasEnvio = archivos.leerBanderaEnvio(pathMedioEnvio);
centrosReparto = archivos.leerCentroReparto(pathCentrRep);
impresiones = archivos.leerCaractImpresion(pathImpresion);
}
for(auto arch : entrs)
{
contadorIteraciones++;
archivo<<contadorIteraciones<<"--Procesando Archivo ENTR: "<<arch<<"----------------------------------------------"<<std::endl;
std::cout<<contadorIteraciones<<"--Procesando Archivo ENTR: "<<arch<<"-------------------------------------------------------------"<<std::endl;
std::cout<<" Procesando.... *"<<std::endl;
// //std::cout<<pathJOUR<<" -- antes del getJournals"<<std::endl;
jours = archivos.getJournals(pathJOUR, arch);
std::string pathUnJour = "";
for (auto jour : jours)
{
archivo<<" -Jour: "<<" -- "<<jour<<std::endl;
journals.clear();
journals = archivos.leeJournal(pathUnJour, jour);
pathUnJour = "";
}
std::string nombreCFD = archivos.archivoRelacionado(pathENTR, arch, "CFD");
if(nombreCFD != "" )
{
CFDS.clear();
CFDS = archivos.leeCFD(pathENTR, nombreCFD);
}
std::string nombreTIM = archivos.archivoRelacionado(pathENTR, arch, "TIM");
if(nombreTIM != "" )
{
TIMS.clear();
TIMS = archivos.leeTIM(pathENTR, nombreTIM);
}
std::string nombreDomiciliacion = archivos.getArchivotS702(pathENTR, arch);
std::string nombreDisp = archivos.getArchivoEPSTDISP(pathENTR, arch);
domicilios.clear();
domicilios = archivos.leerDomiciliacion(pathENTR);
cargos.clear();
cargos = archivos.leerCargosAclaracion(pathENTR);
std::string pathArchivo = pathENTR + "/" + arch;
todosClientes.clear();
todosClientes = ex.extrae(pathArchivo, journals, banderasEnvio, CFDS, TIMS, centrosReparto, domicilios, cargos, impresiones);
archivos.generaArchivo(pathSalida, todosClientes, arch);
std::cout<<" Procesando.... +"<<std::endl;
}
time_t tfin = time(0);
ltm = gmtime(&tfin);
std::string shfin = std::to_string(ltm->tm_hour) + ":" + std::to_string(ltm->tm_min) + ":" + std::to_string(ltm->tm_sec);
archivo<<shfin;
archivo.close();
return 0;
}
by the way, i use a linux base server to compile, thank you everyone!
Related
I've researched a lot for this problem, but I can´t find what exactly is causing the error.
I'm using VS 2017 and this is my header file
#ifndef FUNCTION_H
#define FUNCTION_H
#include <iostream>
#include <vector>
#include <map>
extern "C" {
#include "extApi.h"
}
void BufferToMatrix(simxUChar* buffer, unsigned int** matrix, int dim_fil, int dim_col);
void PrintMatrix(unsigned int** matriz, int dim_fil, int dim_col);
class Graph
{
// representacion por Adjacency List
std::vector<std::vector<int>> graph;
std::map<int, std::vector<int>> neighbors; // Los nodos posibles, orden izquierda, abajo, derecha, arriba
public:
// Constructores crean el numero de nodos basados en una matriz
Graph(unsigned int**, int, int);
~Graph();
};
#endif
and the .cpp file
#include <iostream>
#include <vector>
#include <map>
extern "C" {
#include "extApi.h"
}
using namespace std;
void BufferToMatrix(simxUChar* buffer, unsigned int** matrix, int dim_fil, int dim_col)
{
// Sacamos la data del buffer, dim_fil = res[1] y dim_col = res[0]
for (int i = 0; i < dim_fil; i++) // filas
{
for (int j = 0; j < dim_col; j++) // Columnas
{
matrix[j][dim_fil-1 - i] = buffer[i*dim_col + j]; // Matriz con las filas invertidas... el buffer lo entrega asi.
}
}
}
void PrintMatrix(unsigned int** matriz, int dim_fil, int dim_col)
{
// Imprimimos la matriz en consola
for (int i = 0; i < dim_fil; i++) // filas
{
for (int j = 0; j < dim_col; j++) // columnas
{
cout << matriz[j][i] << " ";
}
cout << endl;
}
}
Graph::Graph(unsigned int** map, int dim_fil, int dim_col) {}
Graph::~Graph() {}
and the main so far
#include <iostream>
#include "function.h"
#include "function.cpp"
extern "C" {
#include "extApi.h"
}
using namespace std;
int main(int argc, char* argv[])
{
// Obtenemos los Handlers enviandos en la llamada del ejecutable
int portNb = 0;
int mappingSensorHandle = 0;
//int leftMotorHandle = 0;
//int rightMotorHandle = 0;
//int graphHandle = 0;
//int proximitySensorHandle = 0;
if (argc >= 3)
{
portNb = atoi(argv[1]);
mappingSensorHandle = atoi(argv[2]);
//leftMotorHandle = atoi(argv[3]);
//rightMotorHandle = atoi(argv[4]);
//graphHandle = atoi(argv[5]);
//proximitySensorHandle = atoi(argv[6]);
}
else
{
cout << "Es necesario indicar los handlers en V-rep" << endl;
extApi_sleepMs(5000);
return 0;
}
// Iniciamos la simulacion
int clientID = simxStart((simxChar*)"127.0.0.1", portNb, true, true, 2000, 5);
if (clientID != -1)
{
// Declaraciones de variables auxiliares
int retVal = 0;
bool OneTimeFlag = 0;
// Declaraciones de variables, lectura del mapa
simxInt res[2]; //res[0] son columnas y res[1] son filas
simxUChar* image; //apuntador al arreglo con la data del sensor de vision
simxUChar options = 1; //en 1 recibe en escala de grises, en 0 recibe en rgb
// Habilitamos el Streaming del mapa
simxGetVisionSensorImage(clientID, mappingSensorHandle, res, &image, options, simx_opmode_streaming);
OneTimeFlag = 1;
// Creamos una matriz dinamica para el mapa
unsigned int** map = new unsigned int* [res[1]];
for (int i = 0; i < res[1]; i++)
{
map[i] = new unsigned int[res[0]];
}
// Loop de la simulacion en V-rep
while (simxGetConnectionId(clientID) != -1)
{
if (OneTimeFlag)
{
retVal = simxGetVisionSensorImage(clientID, mappingSensorHandle, res, &image, options, simx_opmode_buffer);
if (retVal == simx_return_ok)
{
BufferToMatrix(image, map, res[1], res[0]); // Llenamos la matriz
PrintMatrix(map, res[1], res[0]); // Imprimimos la matriz en CMD
OneTimeFlag = 0; // Colocamos la flag en 0 para no ejecutar esta parte
}
// Creamos el grafo y el SpanningTree
//Graph grafo(map, res[1], res[0]);
}
}
// Borramos la matriz del mapa
for (int i = 0; i < res[1]; i++)
{
delete [] map[i];
}
delete [] map;
simxFinish(clientID);
}
else
{
// Terminamos la simulacion, no se realizo la conexion
cout << "Conexion no lograda" << endl;
simxFinish(clientID);
return(0);
}
return(0);
}
this is a script to use a external API in V-rep, the only lines that cause trouble is this two lines in the .h file
std::vector<std::vector<int>> graph;
std::map<int, std::vector<int>> neighbors;
Cause this problems:
Error LNK2001 símbolo externo __imp___CrtDbgReport sin resolver.
Error LNK2001 símbolo externo __imp___invalid_parameter sin resolver.
Error LNK1120 2 externos sin resolver coverageBotClient.
I apologize because this is to simple but I can´t see the error.
I am writing a c++ hdfs client using libhdfs3. the hdfs was kerberized.So I am trying to acquire the kerberos credentials using gssapi. I wrote the bellow sample to do that.
static void
parse_oid(char *mechanism, gss_OID * oid)
{
char *mechstr = 0;
gss_buffer_desc tok;
OM_uint32 maj_stat, min_stat;
size_t i, mechlen = strlen(mechanism);
if (isdigit((int) mechanism[0])) {
mechstr = (char *)malloc(mechlen + 5);
if (!mechstr) {
fprintf(stderr, "Couldn't allocate mechanism scratch!\n");
return;
}
mechstr[0] = '{';
mechstr[1] = ' ';
for (i = 0; i < mechlen; i++)
mechstr[i + 2] = (mechanism[i] == '.') ? ' ' : mechanism[i];
mechstr[mechlen + 2] = ' ';
mechstr[mechlen + 3] = ' ';
mechstr[mechlen + 4] = '\0';
tok.value = mechstr;
} else
tok.value = mechanism;
tok.length = strlen((char*)tok.value);
maj_stat = gss_str_to_oid(&min_stat, &tok, oid);
if (maj_stat != GSS_S_COMPLETE) {
display_status("str_to_oid ", maj_stat, min_stat);
return;
}
if (mechstr)
free(mechstr);
}
static int client_establish_context(gss_OID oid, char *username)
{
gss_buffer_desc send_tok;
OM_uint32 maj_stat, min_stat;
gss_cred_id_t cred = GSS_C_NO_CREDENTIAL;
gss_name_t gss_username = GSS_C_NO_NAME;
gss_OID_set_desc mechs, *mechsp = GSS_C_NO_OID_SET;
if (oid != GSS_C_NO_OID) {
mechs.elements = oid;
mechs.count = 1;
mechsp = &mechs;
} else {
mechs.elements = NULL;
mechs.count = 0;
}
if (username != NULL) {
send_tok.value = username;
send_tok.length = strlen(username);
maj_stat = gss_import_name(&min_stat, &send_tok,
(gss_OID) GSS_KRB5_NT_PRINCIPAL_NAME,
&gss_username);
if (maj_stat != GSS_S_COMPLETE) {
display_status("parsing client name ", maj_stat, min_stat);
printf("Error 1\n");
return -1;
}
}
maj_stat = gss_acquire_cred(&min_stat,
gss_username,
0,
mechsp,GSS_C_INITIATE,
&cred, NULL, NULL);
if (maj_stat != GSS_S_COMPLETE) {
display_status("acquiring creds ", maj_stat, min_stat);
gss_release_name(&min_stat, &gss_username);
printf("Error 2\n");
return -1;
}
gss_release_name(&min_stat, &gss_username);
(void) gss_release_cred(&min_stat, &cred);
}
int main()
{
display_file = stdout;
char *username="hadoop/srinivasanv-ux#SRINI.COM";
char *mechanism = "{ 1 2 840 113554 1 2 2 }";
gss_OID oid;
setenv("KRB5_CLIENT_KTNAME","/home/srini/kafka/keytabs/hadoop.keytab",1);
parse_oid(mechanism, &oid);
if (client_establish_context(oid, username) < 0) {
printf("failed\n");
}
else
{
printf("success\n");
}
}
This documentation says
If no existing tickets are available for the desired name, but the name has an entry in the default client keytab, the krb5 mechanism will acquire initial tickets for the name using the default client keytab.
But I am getting following error
Can't find client principal hadoop/srinivasanv-ux#SRINI.COM in cache collection
what I am doing wrong here?
I wrote a program in C++ for a project and it seems to be giving me some issues running it on my Raspberry Pi 3 B+.
The problem is, the program is actually a countdown timer and it is not supposed to be shut down, but after only 30 minutes, the program stops working.
#include "led-matrix.h"
#include "graphics.h"
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <time.h>
#include <algorithm>
#include <string>
#include <curl/curl.h>
#include <jsoncpp/json/json.h>
#include <jsoncpp/json/reader.h>
#include <jsoncpp/json/writer.h>
#include <jsoncpp/json/value.h>
#include <sstream>
#include <fstream>
#define times 1 //numar de treceri
using namespace std;
using namespace rgb_matrix;
static int usage(const char *progname) {
fprintf(stderr, "usage: %s [options]\n", progname);
fprintf(stderr, "Reads text from stdin and displays it. "
"Empty string: clear screen\n");
fprintf(stderr, "Options:\n");
rgb_matrix::PrintMatrixFlags(stderr);
fprintf(stderr, "\t-f <font-file> : Use given font.\n");
return 1;
}
static int last_id = 53;
Color color(255, 255, 255);
Color color_line(255, 255, 255);
Color color_clock(255, 255, 255);
Color bg_color(0, 0, 0);
const char *bdf_font_file_text = "/home/pi/ct/fonts/9x15B.bdf";
const char *bdf_font_file_clock = "/home/pi/ct/fonts/7x13B.bdf";
const int char_width_text = 9;
const int char_width_clock = 7;
const int char_height_clock = 13;
const string def_message = "100 Pentru Viitor / RomânEști oriunde ai fi!";
int brightness = 100;
int letter_spacing = 0;
int size_of_clock;
string time_result = "";
int year = 100;
int day = 0;
int hour = 0;
int mins = 0;
int sec = 0;
double last_time_text = clock();
double last_time_clock = clock();
double last_time_db = clock();
double last_time_timer = clock();
string last_result = "";
bool countdown = false;
bool random_set = false;
int times_left = times; //numarul de treceri
rgb_matrix::Font font_text;
rgb_matrix::Font font_clock;
char remTime[16];
ofstream timeFile;
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
((std::string *) userp)->append((char *) contents, size * nmemb);
return size * nmemb;
}
// convert int to string (e bine sa stii de el)
static string itos(int i) {
stringstream s;
s << i;
return s.str();
}
//cauta sa vada daca exista deja un timp de la care sa ii dea reset
//preia textul de la API
static string getApiText(int id) {
if (random_set) {
id = 0;
}
try {
CURL *curl;
std::string readBuffer;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, ("http://192.168.0.108/capsula/api.php?order=ASC&id=" + itos(id)).c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(readBuffer.c_str(), root); //parse process
if (!parsingSuccessful) {
std::cout << "Failed to parse"
<< reader.getFormattedErrorMessages();
cout << readBuffer.c_str() << endl << endl;
return def_message;
}
if (root[0].get("mesaj", "") != "Start Capsula-Timpului NOW") {
if (random_set) {
int no = 0 + (rand() % static_cast<int>(root.size() + 1));
cout << "random no is " << no << endl;
cout << "random id is " << root[no].get("id", "").asString() << " and last_id is " << last_id
<< endl << endl;
return root[no].get("mesaj", "").asString();
} else if (!random_set) {
last_id = atoi(root[0].get("id", last_id).asString().c_str());
cout << "last_id is " << last_id << endl;
string result = root[0].get("mesaj", "").asString();
last_result = result;
if (result == "") {
random_set = true;
return "";
} else {
random_set = false;
return result;
}
}
} else {
return def_message;
}
last_id = atoi(root[0].get("id", last_id).asString().c_str());
}
return def_message;
}
catch (const std::exception &e) {
if (last_result != "")
return last_result;
else return def_message;
}
}
//aici e triggerul pt countdown
static void checkCountDownStatus() {
try {
CURL *curl;
std::string readBuffer;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.0.108/capsula/api.php?order=ASC");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(readBuffer.c_str(), root); //parse process
if (!parsingSuccessful) {
std::cout << "Failed to parse"
<< reader.getFormattedErrorMessages();
}
for (unsigned int no = 0; no < root.size(); no++) {
string result = root[no].get("mesaj", "").asString();
if (result == "Start Capsula-Timpului NOW") {
//if (result == "bbb") {
//if (result == "Porneste!") {
countdown = true;
}
}
}
}
catch (const std::exception &e) {}
}
//aici calculeaza timpul ramas in countdown timer
static string getRemainingTime() {
if (!countdown) { //cand nu face countdown, o sa afiseze "100:000:00:00:00"
return "100:000:00:00:00";
}
//basic computation pentru countdown
if (clock() - last_time_timer > 1301236) {
sec--;
if (sec < 0) {
sec = 59;
mins--;
}
if (mins < 0) {
mins = 59;
hour--;
}
if (hour < 0) {
hour = 23;
day--;
}
if (day < 0) {
if (year % 4 == 0)
day = 366;
else day = 365;
year--;
}
if (year < 0) {
countdown = false;
}
last_time_timer = clock();
}
//formatare (pt estetica) a countdown-ului
time_result = "";
if (year < 100 && year > 10) {
time_result = time_result + "0" + itos(year);
} else if (year < 10) {
time_result = time_result + "00" + itos(year);
} else time_result = time_result + itos(year);
time_result = time_result + ":";
if (day < 100 && day > 10) {
time_result = time_result + "0" + itos(day);
} else if (day < 10) {
time_result = time_result + "00" + itos(day);
} else time_result = time_result + itos(day);
time_result = time_result + ":";
if (hour < 10) {
time_result = time_result + "0" + itos(hour);
} else time_result = time_result + itos(hour);
time_result = time_result + ":";
if (mins < 10) {
time_result = time_result + "0" + itos(mins);
} else time_result = time_result + itos(mins);
time_result = time_result + ":";
if (sec < 10) {
time_result = time_result + "0" + itos(sec);
} else time_result = time_result + itos(sec);
std::ofstream out("/home/pi/ct/time.txt");
out << time_result;
out.close();
return time_result;
}
//aici compara last_id cu ultimul id din baza de date
static void compareIdToDB() {
try {
CURL *curl;
std::string readBuffer;
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, ("http://192.168.0.108/capsula/api.php?order=ASC&id=" + itos(last_id)).c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2L);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse(readBuffer.c_str(), root); //parse process
if (!parsingSuccessful) {
std::cout << "Failed to parse" << reader.getFormattedErrorMessages();
}
int id = atoi(root[0].get("id", -1).asString().c_str());
if (id > -1) {
random_set = false;
cout << "Found new entry" << endl;
}
}
}
catch (const std::exception &e) {}
}
//aici isi face load la fonturi
static int loadFonts() {
if (!font_text.LoadFont(bdf_font_file_text)) {
fprintf(stderr, "Couldn't load text font '%s'\n", bdf_font_file_text);
return 1;
}
if (!font_clock.LoadFont(bdf_font_file_clock)) {
fprintf(stderr, "Couldn't load clock font '%s'\n", bdf_font_file_clock);
return 1;
}
return 0;
}
//aici e main-ul
int main(int argc, char *argv[]) {
RGBMatrix::Options matrix_options;
rgb_matrix::RuntimeOptions runtime_opt;
if (!rgb_matrix::ParseOptionsFromFlags(&argc, &argv, &matrix_options, &runtime_opt)) {
return usage(argv[0]);
}
loadFonts();
RGBMatrix *canvas = rgb_matrix::CreateMatrixFromOptions(matrix_options, runtime_opt);
if (canvas == NULL)
return 1;
canvas->SetBrightness(brightness);
canvas->SetPWMBits(1);
int panel_size = 512;
int x = panel_size;
string remTimeString;
string temp = getApiText(last_id);
char line[1024];
strncpy(line, temp.c_str(), sizeof(line));
line[sizeof(line) - 1] = 0;
int text_offset = (1024 - std::count(line, line + 1024, 0)) * char_width_text;
while (true) {
if (clock() - last_time_text > 50000) { //delay intre schimbare de pixeli
last_time_text = clock();
if (x > 0 - text_offset) {
x--;
} else {
times_left--;
x = panel_size;
if (times_left <= 0) {
temp = getApiText(last_id);
strncpy(line, temp.c_str(), sizeof(line));
line[sizeof(line) - 1] = 0;
text_offset = (1024 - std::count(line, line + 1024, 0)) * char_width_text;
times_left = times; //numar de treceri
}
}
}
if (clock() - last_time_clock > 1301236) { //delay intre "secunde"
remTimeString = getRemainingTime();
size_of_clock = remTimeString.size();
strncpy(remTime, remTimeString.c_str(), sizeof(remTime));
last_time_clock = clock();
if (!countdown)
checkCountDownStatus();
}
if (clock() - last_time_db > CLOCKS_PER_SEC && (random_set)) { //delay intre comaparari la baza de date
compareIdToDB();
last_time_db = clock();
}
rgb_matrix::DrawText(canvas, font_text, x, 16 + font_text.baseline(),
color, &bg_color, line,
letter_spacing);
//draw line
rgb_matrix::DrawLine(canvas, 0, 14, panel_size, 14, color_line);
rgb_matrix::DrawLine(canvas, 0, 15, panel_size, 15, color_line);
//show clock
rgb_matrix::DrawText(canvas, font_clock, 126 - (size_of_clock * char_width_clock) - 6, 12,
color_clock, &bg_color, remTime,
letter_spacing);
rgb_matrix::DrawText(canvas, font_clock, 254 - (size_of_clock * char_width_clock) - 6, 12,
color_clock, &bg_color, remTime,
letter_spacing);
rgb_matrix::DrawText(canvas, font_clock, 382 - (size_of_clock * char_width_clock) - 6, 12,
color_clock, &bg_color, remTime,
letter_spacing);
rgb_matrix::DrawText(canvas, font_clock, 510 - (size_of_clock * char_width_clock) - 6, 12,
color_clock, &bg_color, remTime,
letter_spacing);
}
}
Is there any way to tell Raspbian (the OS) that it should NOT pause the process?
I'm just speaking my mind out here, honestly I have no idea what is going on.
The worst part, the problem started showing up 1 hour before the countdown is supposed to start...
I have to use an IDS uEye Camera mod. UI1210SE-C under visual c++ 2010 and OpenCV
I need to take a photo every time there is a request by a client, so when I need, I need to take a simple single shot, that I need to save in a OpenCV Mat image.
How do this?
I have download SDK, and initialize camera, that have been recognized by my PC, but I don't understand how take a photo and how save in a Mat without issues
This is my actual code, works but Images are RED tone and not different, but first and second are equal, third different...I don't understand why...
#define CAPTURE_WIDTH 500
#define CAPTURE_HEIGHT 375
//Allocazione della matrice immagine per il frame catturato dalla telecamera
Mat frame(CAPTURE_HEIGHT, CAPTURE_WIDTH,CV_8UC3);
//Variabili di inizializzazione della Telecamera IDS uEye UI1220SE-C
HIDS hCam = 1; //Apre Camera con ID 1
int BITS_PER_PIXEL = 24;
int pWidth = CAPTURE_WIDTH;
int pHeight = CAPTURE_HEIGHT;
SENSORINFO sensor_info;
CAMINFO camera_info;
//puntatori memoria
char* m_pcImageMemory;
int m_lMemoryId;
//Pulizia memoria da foto precedenti
if (hCam != 0){
is_FreeImageMem (hCam,m_pcImageMemory,m_lMemoryId);
is_ExitCamera(hCam);
}
//inizializzazione della telecamera
int initcamera = is_InitCamera(&hCam, NULL);
if(initcamera != IS_SUCCESS)
{
cout<<endl<<"Impossibile inizializzare la telecamera"<<endl;
exit(-1);
}
// Acquisisce informazioni riguardanti la telecamera
int camerainfo = is_GetCameraInfo (hCam, &camera_info);
if(camerainfo != IS_SUCCESS)
{
printf("Impossibile acquisire le informazioni della telecamera");
exit(-1);
}
// Acquisisce informazioni riguardanti il sensore della telecamera
int sensorinfo = is_GetSensorInfo (hCam, &sensor_info);
if(sensorinfo != IS_SUCCESS)
{
printf("Impossibile acquisire le informazioni del sensore");
exit(-1);
}
//Output informazioni camera/sensore
cout<<endl<<"<<< CARATTERISTICHE DELLA TELECAMERA COLLEGATA >>>"<<endl;
cout<<"Numero seriale: " << camera_info.SerNo << endl;
cout << "Produttore: " << camera_info.ID << endl;
cout << "Modello: " << sensor_info.strSensorName << endl;
cout << "Dimensioni massime per l'immagine: " << sensor_info.nMaxWidth << "x" << sensor_info.nMaxHeight << endl << endl;
//Imposta la modalità di colore BGR24
int colormode = is_SetColorMode(hCam, IS_CM_BGR8_PACKED);
//int colormode = is_SetColorMode(hCam, IS_SET_CM_RGB24);
if(colormode != IS_SUCCESS)
{
printf("Impossibile impostare il modo di colore");
exit(-1);
}
//imposta dimensioni immagini che voglio catturare
int pXPos = (sensor_info.nMaxWidth);
int pYPos = (sensor_info.nMaxHeight);
//Inizializzazione Memoria camera
int rit = is_AllocImageMem (hCam,pXPos,pYPos, 24, &m_pcImageMemory, &m_lMemoryId);
if(rit != IS_SUCCESS)
{
cout<<endl<<"IMPOSSIBILE INIZIALIZZARE LA MEMORIA"<<endl;
system("PAUSE");
exit(-1);
}
cout<<endl<<"Memoria inizializzata"<<endl;
//attivazione della locazione di memoria
int rat = is_SetImageMem (hCam, m_pcImageMemory, m_lMemoryId);
if(rat != IS_SUCCESS)
{
cout<<endl<<"IMPOSSIBILE ATTIVARE LA MEMORIA"<<endl;
system("PAUSE");
exit(-1);
}
cout<<endl<<"Memoria Attivata"<<endl;
//impostazioni correzioni di colore
double strenght_factor = 1.0;
int colorcorrection = is_SetColorCorrection(hCam, IS_CCOR_ENABLE, &strenght_factor);
//impostazioni correzione del bianco
double pval = 1;
int whiteb = is_SetAutoParameter(hCam, IS_SET_ENABLE_AUTO_WHITEBALANCE, &pval, 0);
//impostazione della correzione guadagno
double gval = 1;
int gains = is_SetAutoParameter(hCam, IS_SET_ENABLE_AUTO_GAIN, &gval, 0);
//inizio fase cattura immagine
int dummy;
char *pMem, *pLast;
//ciclo di ripetizione
for (int i=0;i<3;i++)
{
int sho = is_FreezeVideo(hCam, IS_WAIT);
if(sho != IS_SUCCESS)
{
cout<<endl<<"IMPOSSIBILE ACQUISIRE DALLA TELECAMERA"<<endl;
system("PAUSE");
exit(-1);
}
if (sho == IS_SUCCESS){
int m_Ret = is_GetActiveImageMem(hCam, &pLast, &dummy);
int n_Ret = is_GetImageMem(hCam, (void**)&pLast);
}
IplImage* tmpImg = cvCreateImageHeader(cvSize (pXPos, pYPos), IPL_DEPTH_8U,3);
tmpImg->imageData = m_pcImageMemory;
frame = cv::cvarrToMat(tmpImg);
imshow("PROVA",frame);
waitKey(0);
}
//chiusura e pulizia della telecamera
int en = is_ExitCamera(hCam);
if (en == IS_SUCCESS){
cout<<endl<<"Camera chiusa correttamente"<<endl;
}
is_freezeVideo is the function that doing snapshot (reading manual) but I don't understand why pictures are RED and how use in a mat file insted passing from a iplimage....
Thanks in advance to all can help me...
Hmm I tested your code on my pc and everything is working perfectly. The images are maintaining the same parameters and I get the correct outcome.
Maybe the problem is that you don't define a parameter file (.ini). In order to do it you have to define it on your own as is said in the manual and call it with the
INT is_ParameterSet(HIDS hCam, UINT nCommand, void* pParam, UINT cbSizeOfParam)
I tested it on Ubuntu 12.04, Eclipse IDE for C/C++ Developers Version: Kepler Service Release 2 with ueye Version 4.31.
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!