void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

	region_type format;
	region_container* p;
	region_container* c;

	if( nrhs != 2 ) mexErrMsgTxt("Two vector arguments (region and format) required.");
	if( nlhs != 1 ) mexErrMsgTxt("Exactly one output argument required.");

	if (mxGetClassID(prhs[0]) != mxDOUBLE_CLASS)
		mexErrMsgTxt("First input argument must be of type double");

	if ( mxGetNumberOfDimensions(prhs[0]) > 2 || mxGetM(prhs[0]) > 1 ) mexErrMsgTxt("First input argument must be a vector");

    char* codestr = get_string(prhs[1]);

	if (!get_region_code(codestr, format)) {
        free(codestr);
		mexErrMsgTxt("Not a valid format");
    }

    free(codestr);

	p = array_to_region(prhs[0]);

	if (!p)
		mexErrMsgTxt("Not a valid region vector");

	c = region_convert(p, format);

	if (!c) {
		if (p) region_release(&p);
		mexErrMsgTxt("Unable to convert region");
	}

    plhs[0] = region_to_array(c);

	if (c) region_release(&c);
	if (p) region_release(&p);
}
Esempio n. 2
0
void			mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  /* B=imResample(A,scale) or B=imResample(A,h,w); */
  double input1=0, input2=0; int *ns, ms[3], nCh, nDims, i;
  double *A, *B, *T; void *A1, *B1; mxClassID id;
  
  /* Error checking on arguments */
  if( nrhs<2 || nrhs>3) mexErrMsgTxt("Two or three inputs expected.");
  if( nlhs>1 ) mexErrMsgTxt("One output expected.");
  nDims=mxGetNumberOfDimensions(prhs[0]); id=mxGetClassID(prhs[0]);
  if( (nDims!=2 && nDims!=3) || (id!=mxDOUBLE_CLASS && id!=mxUINT8_CLASS) )
    mexErrMsgTxt("A should be 2D or 3D double or uint8 array.");
  input1=mxGetScalar(prhs[1]); if(nrhs>=3) input2=mxGetScalar(prhs[2]);
  
  /* create output array */
  ns = (int*) mxGetDimensions(prhs[0]); nCh=(nDims==2) ? 1 : ns[2]; ms[2]=nCh;
  if( nrhs==2 ) {
    ms[0]=(int) (ns[0]*input1+.5); ms[1]=(int) (ns[1]*input1+.5);
  } else {
    ms[0]=(int) input1; ms[1]=(int) input2;
  }
  plhs[0] = mxCreateNumericArray(3, ms, id, mxREAL);
  
  /* convert to double if id!=mxDOUBLE_CLASS */
  A1=mxGetData(prhs[0]); B1=mxGetData(plhs[0]);
  if( id==mxDOUBLE_CLASS ) { A=(double*) A1; B=(double*) B1; } else {
    A = (double*) mxMalloc( ns[0]*ns[1]*nCh*sizeof(double) );
    B = (double*) mxCalloc( ms[0]*ms[1]*nCh, sizeof(double) );
  }
  if(id==mxUINT8_CLASS) for(i=0; i<ns[0]*ns[1]*nCh; i++) A[i]=(double) ((uchar*)A1)[i];
  
  /* Perform rescaling */
  T = (double*) mxCalloc(ms[0]*ns[1]*nCh, sizeof(double) );
  resample( A, T, ns[0], ms[0], ns[1], nCh );
  resample( T, B, ns[1], ms[1], ms[0], nCh );
  mxFree(T);
  
  /* convert from double if id!=mxDOUBLE_CLASS */
  if(id==mxUINT8_CLASS) for(i=0; i<ms[0]*ms[1]*nCh; i++) ((uchar*)B1)[i]=(uchar) (B[i]+.5);
  if( id!=mxDOUBLE_CLASS ) { mxFree(A); mxFree(B); }
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if (nrhs != 2)
    mexErrMsgTxt("Two inputs required.");

  btkMXCheckNoOuput(nlhs, plhs); // Only when there is no output for the function.

  if ((mxGetClassID(prhs[1]) != mxDOUBLE_CLASS) || mxIsEmpty(prhs[1]) || mxIsComplex(prhs[1]))
    mexErrMsgTxt("The second input must be a matrix of real (double) values corresponding to points values."); 

  // First output
  btk::Acquisition::Pointer acq = btk_MOH_get_object<btk::Acquisition>(prhs[0]);

  int numberOfValuesPerPoint = acq->GetPointFrameNumber() * 3;
  int numberOfPoints = acq->GetPointNumber();

  if (mxGetNumberOfElements(prhs[1]) != numberOfPoints*numberOfValuesPerPoint)
    mexErrMsgTxt("The second input doesn't have the same size than the number of points values.");
    
  double* values = mxGetPr(prhs[1]);

  int i = 0;
  int j = numberOfValuesPerPoint;
  double* v = 0;
  btk::Acquisition::PointIterator it = acq->BeginPoint();
  while (i < numberOfPoints * numberOfValuesPerPoint)
  {
    if (j >= numberOfValuesPerPoint)
    {
      v = (*it)->GetValues().data();
      ++it;
      j = 0;
    }
    v[j] = values[i];
    v[j+1] = values[i+1];
    v[j+2] = values[i+2];
    i+=3; j+=3;
  }
};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if(nrhs < 2)
    mexErrMsgTxt("Two inputs required.");
  if (nlhs > 1)
    mexErrMsgTxt("Too many output arguments.");

  for (int i = 1 ; i < nrhs ; ++i)
  {
    if (mxIsEmpty(prhs[i]) || (!mxIsChar(prhs[i]) && ((mxGetClassID(prhs[i]) != mxDOUBLE_CLASS) || mxIsComplex(prhs[i]) || (mxGetNumberOfElements(prhs[i]) != 1))))
      mexErrMsgTxt("Metadata's label or index must be set by a non-empty string or an integer (double value) respectively.");
  }
  
  btk::Acquisition::Pointer acq = btk_MOH_get_object<btk::Acquisition>(prhs[0]);
  btk::MetaData::Iterator it;
  btk::MetaData::Pointer parent = btkMXExtractMetaDataIterator(&it, nrhs-1,  prhs, acq->GetMetaData());
  
  parent->RemoveChild(it);
  
  if (nlhs > 0)
    plhs[0] = btkMXCreateMetaDataStructure(acq->GetMetaData());
};
void sendString(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  NetClient *nc = GetNetClient(nrhs, prhs);

  if(nrhs != 2)		mexErrMsgTxt("Two arguments required: handle, string.");
  //if(nlhs < 1) mexErrMsgTxt("One output argument required.");
  if(mxGetClassID(prhs[1]) != mxCHAR_CLASS)
	  mexErrMsgTxt("Argument 2 must be a string.");

  char *tmp = mxArrayToString(prhs[1]);
  std::string theString (tmp);
  mxFree(tmp);

  try {
    nc->sendString(theString);
  } catch (const SocketException & e) {
    const std::string why (e.why());
    if (why.length()) mexWarnMsgTxt(why.c_str());
    RETURN_NULL();
  }
  RETURN(1);
}
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
   
  if (nrhs!=2)	mexErrMsgTxt("Two inputs required");

  //check class
  mxClassID classID = mxGetClassID(dataIn);
  
  //get dimensions  
  mwSize ndims = mxGetM(dataIn);
  mwSize npoints = mxGetN(dataIn);
  
  //get metric
  char tt[100];
  NormalizeMetric metric;
  mxGetString(metricIn, tt, 90);
  string metricStr(tt);
  if (metricStr=="l1")            metric = NORMALIZE_METRIC_L1;
  else if (metricStr=="l2")       metric = NORMALIZE_METRIC_L2;
  else                            metric = NORMALIZE_METRIC_NONE; 
//    mexErrMsgTxt("Unknown distance function.");

  //allocate output
  dataOut = mxDuplicateArray(dataIn);  //(mxArray*)dataIn; //
  
  //call agg cluster  
#define __CASE(CLASS)                                                   \
  {                                                                     \
    /*get data*/                                                        \
    Data<TYPEOF_##CLASS> data;                                          \
    fillData(data, dataOut);                                            \
    /*normalize*/                                                       \
    normalize(data, metric);                                            \
  }
            
    __SWITCH(classID, __CASE)    
    
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if(nrhs > 4)
    mexErrMsgTxt("Too many input arguments.");
  if (nlhs > 1)
    mexErrMsgTxt("Too many output arguments.");

  int pn = 0, fn = 0, an = 0, r = 1;
  
  for (int i = 0 ; i < nrhs ; ++i)
  {
    if ((mxGetClassID(prhs[i]) != mxDOUBLE_CLASS) || mxIsEmpty(prhs[i]) || mxIsComplex(prhs[i])
        || (mxGetNumberOfElements(prhs[i]) != 1))
      mexErrMsgTxt("All input arguments must be set to double values representing integers.");
  }
  if (nrhs >= 1)
    pn = static_cast<int>(mxGetScalar(prhs[0]));
  if (nrhs >= 2)
    fn = static_cast<int>(mxGetScalar(prhs[1]));
  if(nrhs >= 3)
    an = static_cast<int>(mxGetScalar(prhs[2]));
  if(nrhs >= 4)
    r = static_cast<int>(mxGetScalar(prhs[3]));
  
  if (r == 0)
    mexErrMsgTxt("Impossible to set the analog sample number by point frame to 0.");

  btk::Acquisition::Pointer acq = btk::Acquisition::New();
  acq->Init(pn, fn, an, r);
  plhs[0] = btk_MOH_create_handle(acq);
  
#if defined(__APPLE__) || (defined(BTK_BUILD_SHARED_LIBS) && defined(__unix__))
  // It seems to be related only to Linux with shared libraries
  // This fix was only tested with Matlab r2009a (7.8)
  // FIXME: This solution clear all the acquisitions and not only the ones 
  //        created from this function
  mexAtExit(btk::MEXHandleCollector<btk::Acquisition>::ManualClear);
#endif
};
Esempio n. 8
0
int bind_int64(sqlite3_stmt *stmt, int index, const mxArray *array)
{
    int64_t val = 0;
    TYPECHECK(array,
              mxINT16_CLASS, mxUINT16_CLASS,
              mxINT32_CLASS, mxUINT32_CLASS,
              mxINT64_CLASS, mxUINT64_CLASS);

    mxClassID cls = mxGetClassID(array);
#define GET_VALUE(CLASS, TYPE) \
    if (cls == CLASS) { \
        TYPE *p = mxGetData(array); \
        val = *p; \
    }
    GET_VALUE(mxINT16_CLASS, int16_t);
    GET_VALUE(mxUINT16_CLASS, uint16_t);
    GET_VALUE(mxINT16_CLASS, int32_t);
    GET_VALUE(mxUINT16_CLASS, uint32_t);
    GET_VALUE(mxINT16_CLASS, int64_t);
    GET_VALUE(mxUINT16_CLASS, uint64_t);
    return sqlite3_bind_int64(stmt, index, val);
}
static void* calcSize(mxArray* data, uint64_t* size) {

    uint64_t numel = mxGetNumberOfElements(data);
    switch (mxGetClassID(data)) {
        case mxLOGICAL_CLASS: ;
        case mxINT8_CLASS:
        case mxUINT8_CLASS:
            *size = numel;
            return mxGetData(data);
        case mxCHAR_CLASS:
            *size = numel * sizeof(mxChar);
            return mxGetChars(data);
        case mxDOUBLE_CLASS:
            *size = numel * sizeof(double);
            return mxGetPr(data);
        case mxSINGLE_CLASS:
            *size = numel * sizeof(float);
            return mxGetData(data);
        case mxINT16_CLASS:
        case mxUINT16_CLASS:
            *size = numel * sizeof(short);
            return mxGetData(data);
        case mxINT32_CLASS:
        case mxUINT32_CLASS:
            *size = numel * sizeof(int);
            return mxGetData(data);
        case mxINT64_CLASS:
        case mxUINT64_CLASS:
            *size = numel * sizeof(int64_t);
            return mxGetData(data);
        default: {
            char s[256];
            sprintf(s, "GridFS - Unsupported type (%s)\n", mxGetClassName(data));
            mexErrMsgTxt(s);
            return 0;
        }
    }
}
void mexFunction(int nlhs, mxArray* plhs[],
                 const int nrhs, const mxArray* prhs[]) {
  
  if (nrhs != 2) {
    mexErrMsgTxt("2 arguments required.");
  }
  
  const int H = mxGetM(prhs[ARG_REGIONS]);
  const int W = mxGetN(prhs[ARG_REGIONS]);
  const int N = H * W;
  
  // Next, check that the data types are correct.
  if (mxGetClassID(prhs[ARG_REGIONS]) != mxINT32_CLASS) {
    mexErrMsgTxt("imgRegionsTrue must be a 'int32'");
  }

  int* regions = (int*) mxGetData(prhs[ARG_REGIONS]);
  int R = (int) mxGetScalar(prhs[ARG_NUM_REGIONS]);

  plhs[0] = mxCreateDoubleMatrix(R, 1, mxREAL);
  double* pixel_counts = (double*) mxGetData(plhs[0]);
  
  for (int ii = 0; ii < N; ++ii, ++regions) {
    int region_id = *regions;
    
    if (region_id == 0) {
      continue;
    }
    
    if (region_id > R) {
      mexErrMsgTxt("Region ID exceeds number of total regions.");
    }
    
    --region_id;
    
    ++pixel_counts[region_id];
  }
}
Esempio n. 11
0
// [Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter); - helper for opticalFlow
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  size_t h, w, nIter; float *Is[4], *Vx, *Vy;

  // Error checking on arguments
  if( nrhs!=5 ) mexErrMsgTxt("Five inputs expected.");
  if( nlhs!=2 ) mexErrMsgTxt("Two outputs expected.");
  h = mxGetM(prhs[0]); w = mxGetN(prhs[0]);
  for( int i=0; i<4; i++ ) {
    if(mxGetM(prhs[i])!=h || mxGetN(prhs[i])!=w) mexErrMsgTxt("Invalid dims.");
    if(mxGetClassID(prhs[i])!=mxSINGLE_CLASS) mexErrMsgTxt("Invalid type.");
    Is[i] = (float*) mxGetData(prhs[i]);
  }
  nIter = (int) mxGetScalar(prhs[4]);

  // create output matricies
  plhs[0] = mxCreateNumericMatrix(int(h),int(w),mxSINGLE_CLASS,mxREAL);
  plhs[1] = mxCreateNumericMatrix(int(h),int(w),mxSINGLE_CLASS,mxREAL);
  Vx = (float*) mxGetData(plhs[0]);
  Vy = (float*) mxGetData(plhs[1]);

  // run optical flow
  opticalFlowHsMex(Vx,Vy,Is[0],Is[1],Is[2],Is[3],int(h),int(w),nIter);
}
Esempio n. 12
0
//--------------------------------------------------------------
// ClassIDText() - Simply return the name of the class
//--------------------------------------------------------------
char *ClassIDText(const mxArray *pArray)
{
  switch(mxGetClassID(pArray))
  {
  case mxUNKNOWN_CLASS : return "UNKNOWN";
  case mxCELL_CLASS    : return "CELL";
  case mxFUNCTION_CLASS: return "FUNCTION";
    //case mxOBJECT_CLASS  : return "OBJECT";
  case mxSTRUCT_CLASS  : return "STRUCT";
  case mxCHAR_CLASS    : return "CHAR";
  case mxLOGICAL_CLASS : return "LOGICAL";
  case mxDOUBLE_CLASS  : return "DOUBLE";
  case mxSINGLE_CLASS  : return "SINGLE";
  case mxINT8_CLASS    : return "INT8";
  case mxUINT8_CLASS   : return "UINT8";
  case mxINT16_CLASS   : return "INT16";
  case mxUINT16_CLASS  : return "UINT16";
  case mxINT32_CLASS   : return "INT32";
  case mxUINT32_CLASS  : return "UINT32";
  case mxINT64_CLASS   : return "INT64";
  default: return "INVALID";
  }
} // end ClassIDText()
Esempio n. 13
0
/* Determine the category (class) of the input array_ptr, and then
   branch to the appropriate analysis routine. */
mxClassID analyze_class(const mxArray *array_ptr)
{
    mxClassID  category;
    
    category = mxGetClassID(array_ptr);
    
    if (mxIsSparse(array_ptr)) {
       analyze_sparse(array_ptr);
    } else {
       switch (category) {
          case mxLOGICAL_CLASS: analyze_logical(array_ptr);    break;
          case mxCHAR_CLASS:    analyze_string(array_ptr);     break;
          case mxSTRUCT_CLASS:  analyze_structure(array_ptr);  break;
          case mxCELL_CLASS:    analyze_cell(array_ptr);       break;
          case mxUNKNOWN_CLASS: 
              mexWarnMsgIdAndTxt("MATLAB:explore:unknownClass", 
                      "Unknown class.");                       break;
          default:              analyze_full(array_ptr);       break;
       }
    }
    
    return(category);
}
Esempio n. 14
0
// H=gradHist(M,O,[bin],[nOrients],[softBin],[useHog],[clip])-see gradientHist.m
void mGradHist( int nl, mxArray *pl[], int nr, const mxArray *pr[] ) {
  int h, w, d, hb, wb, bin, nOrients; bool softBin, useHog;
  float *M, *O, *H, *G, clip;
  checkArgs(nl,pl,nr,pr,1,3,2,7,&h,&w,&d,mxSINGLE_CLASS,(void**)&M);
  O = (float*) mxGetPr(pr[1]);
  if( mxGetM(pr[1])!=h || mxGetN(pr[1])!=w || d!=1 ||
    mxGetClassID(pr[1])!=mxSINGLE_CLASS ) mexErrMsgTxt("M or O is bad.");
  bin      = (nr>=3) ? (int)   mxGetScalar(pr[2])    : 8;
  nOrients = (nr>=4) ? (int)   mxGetScalar(pr[3])    : 9;
  softBin  = (nr>=5) ? (bool) (mxGetScalar(pr[4])>0) : true;
  useHog   = (nr>=6) ? (bool) (mxGetScalar(pr[5])>0) : false;
  clip     = (nr>=7) ? (float) mxGetScalar(pr[6])    : 0.2f;
  hb=h/bin; wb=w/bin;
  if( useHog==false ) {
    pl[0] = mxCreateMatrix3(hb,wb,nOrients,mxSINGLE_CLASS,1,(void**)&H);
    gradHist( M, O, H, h, w, bin, nOrients, softBin );
  } else {
    pl[0] = mxCreateMatrix3(hb,wb,nOrients*4,mxSINGLE_CLASS,1,(void**)&G);
    H = (float*) mxCalloc(wb*hb*nOrients,sizeof(float));
    gradHist( M, O, H, h, w, bin, nOrients, softBin );
    hog( H, G, h, w, bin, nOrients, clip ); mxFree(H);
  }
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if (nrhs != 3)
    mexErrMsgTxt("Three inputs required.");
  if (nlhs > 2)
    mexErrMsgTxt("Too many output arguments.");

  if ((mxGetClassID(prhs[2]) != mxDOUBLE_CLASS) || mxIsEmpty(prhs[2]) || mxIsComplex(prhs[2]))
    mexErrMsgTxt("The third input must be a vector of real (double) values corresponding to the data of one analog channel."); 

  btk::Acquisition::Pointer acq = btk_MOH_get_object<btk::Acquisition>(prhs[0]);
  btk::Analog::Pointer analog = btkMXGetAnalog(acq, nrhs, prhs);
  int numberOfFrames = analog->GetFrameNumber();
  if (mxGetNumberOfElements(prhs[2]) != numberOfFrames)
    mexErrMsgTxt("The third input doesn't have the same number of element than the number of analog frames.");
    
  double* values = mxGetPr(prhs[2]);
  for (int i = 0 ; i < numberOfFrames ; ++i)
    analog->GetValues().coeffRef(i) = values[i];
  
  // Return updated analog channels
  btkMXCreateAnalogsStructure(acq, nlhs, plhs);
};
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  if (nrhs != 2)
    mexErrMsgTxt("Two inputs required.");

  btkMXCheckNoOuput(nlhs, plhs); // Only when there is no output for the function.

  if ((mxGetClassID(prhs[1]) != mxDOUBLE_CLASS) || mxIsEmpty(prhs[1]) || mxIsComplex(prhs[1]))
    mexErrMsgTxt("The second input must be a matrix of real (double) values corresponding to the new analog channels values to assign.");

  // First output
  btk::Acquisition::Pointer acq = btk_MOH_get_object<btk::Acquisition>(prhs[0]);

  int numberOfFrames = acq->GetAnalogFrameNumber();
  int numberOfChannels = acq->GetAnalogNumber();

  if (mxGetNumberOfElements(prhs[1]) != (numberOfFrames * numberOfChannels))
    mexErrMsgTxt("The second input doesn't have the same size than the number of analog channels values.");
    
  double* values = mxGetPr(prhs[1]);

  int i = 0;
  int j = numberOfFrames;
  double* v = 0;
  btk::Acquisition::AnalogIterator it = acq->BeginAnalog();
  while (i < (numberOfFrames * numberOfChannels))
  {
    if (j >= numberOfFrames)
    {
      v = (*it)->GetValues().data();
      ++it;
      j = 0;
    }
    v[j] = values[i];
    ++i; ++j;
  }
};
Esempio n. 17
0
void
mexFunction (int nlhs, mxArray* plhs[],
             int nrhs, const mxArray* prhs[])
{
  mwSize n;
  mwIndex i;
  double *vri, *vro;

  if (nrhs != 1 || ! mxIsNumeric (prhs[0]))
    mexErrMsgTxt ("ARG1 must be a matrix");

  n = mxGetNumberOfElements (prhs[0]);
  plhs[0] = mxCreateNumericArray (mxGetNumberOfDimensions (prhs[0]),
                                  mxGetDimensions (prhs[0]),
                                  mxGetClassID (prhs[0]),
                                  mxIsComplex (prhs[0]));
  vri = mxGetPr (prhs[0]);
  vro = mxGetPr (plhs[0]);

  if (mxIsComplex (prhs[0]))
    {
      double *vii, *vio;
      vii = mxGetPi (prhs[0]);
      vio = mxGetPi (plhs[0]);

      for (i = 0; i < n; i++)
        {
          vro[i] = vri[i] * vri[i] - vii[i] * vii[i];
          vio[i] = 2 * vri[i] * vii[i];
        }
    }
  else
    {
      for (i = 0; i < n; i++)
        vro[i] = vri[i] * vri[i];
    }
}
Esempio n. 18
0
const char* get_mx_class_name(const mxArray *array)
{
    mxClassID   category;

    category = mxGetClassID(array);
    switch (category)  {
        case mxINT8_CLASS: return "int8";
        case mxUINT8_CLASS: return "uint8";
        case mxINT16_CLASS: return "int16";
        case mxUINT16_CLASS:return "uint16";
        case mxINT32_CLASS: return "int32";
        case mxUINT32_CLASS: return "uint32";
        case mxINT64_CLASS:  return "int64";
        case mxUINT64_CLASS:return "uint64";
        case mxSINGLE_CLASS: return "single";
        case mxDOUBLE_CLASS:return "double";
        case mxLOGICAL_CLASS: return "logical";
        case mxCHAR_CLASS:    return "char";
        case mxSTRUCT_CLASS: return "struct";
        case mxCELL_CLASS:   return "cell";
        case mxUNKNOWN_CLASS: return "unknownclass";
        default: return "mysteryclass???";
    }
}
Esempio n. 19
0
static VlHIKMTree*  
matlab_to_hikm (mxArray const *mtree, int method_type)
{
  VlHIKMTree *tree ;
  mxArray *mK, *mdepth ;
  int K = 0, depth = 0;

  VL_USE_MATLAB_ENV ;

  if (mxGetClassID (mtree) != mxSTRUCT_CLASS) {
    mexErrMsgTxt("TREE must be a MATLAB structure.") ;
  }
  
  mK       = mxGetField(mtree, 0, "K") ;
  mdepth   = mxGetField(mtree, 0, "depth") ;
  
  if (!mK                        ||
      !uIsRealScalar (mK)        ||
      (K = (int) *mxGetPr (mK)) < 1) {
    mexErrMsgTxt("TREE.K must be a DOUBLE not smaller than one.") ;
  }
  
  if (!mdepth                    ||
      !uIsRealScalar (mdepth)    ||
      (depth = (int) *mxGetPr (mdepth)) < 1) {
    mexErrMsgTxt("TREE.DEPTH must be a DOUBLE not smaller than one.") ;
  }
  
  tree         = mxMalloc (sizeof(VlHIKMTree)) ;  
  tree-> depth = depth ;
  tree-> K     = K ;
  tree-> M     = -1 ; /* to be initialized later */
  tree-> method= method_type ;
  tree-> root  = xcreate (tree, mtree, 0) ;
  return tree ;
}
Esempio n. 20
0
/* here comes the main function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    int ne, ncells;
    const int *dim;

    mxChar *glued, gluechar;
    const mxChar *toglue;
    const mxChar *glue;
    const mxChar defglue[1] = {CHAR_LF};
    const mxArray *snippet, *togluec;

    int odim[2] = {1, 0};
    signed long gluelen = 1, copypos = 0, totallen = 0, sc = 0;
    bool endterm = 0;

    /* check argument count and content */
	if (nrhs < 1 || nrhs > 3 || nlhs > 1)
		mexErrMsgTxt("Bad number of input/output arguments.");
    if (mxGetClassID(*prhs) != mxCELL_CLASS)
		mexErrMsgTxt("First input must be a cell array.");
    togluec = *prhs;
    ncells = mxGetNumberOfElements(togluec);
    if (ncells == 0) {
        *odim = 0;
        *plhs = mxCreateCharArray(2, odim);
        return;
    }
    glue = defglue;
    if ((nrhs > 1) &&
        (mxGetClassID(prhs[1]) == mxCHAR_CLASS)) {
        dim = mxGetDimensions(prhs[1]);
        if ((dim[1] > 0) &&
            (dim[1] == mxGetNumberOfElements(prhs[1]))) {
            glue = (const mxChar *) mxGetData(prhs[1]);
            gluelen = dim[1];
        }
    }
    if (nrhs > 2) {
        if ((mxGetClassID(prhs[2]) == mxLOGICAL_CLASS) &&
            (mxGetNumberOfElements(prhs[2]) == 1))
            endterm = (*((unsigned char *) mxGetData(prhs[2])) != 0);
    }

    /* count real snippets and length */
    for (; sc < ncells; ++sc) {
        snippet = mxGetCell(togluec, sc);
        if (mxGetClassID(snippet) != mxCHAR_CLASS)
            mexErrMsgTxt("All cells must be of type char.");
        totallen += mxGetNumberOfElements(snippet);
    }
    totallen += gluelen * ((endterm) ? (ncells) : (ncells - 1));

    /* create output */
    odim[1] = totallen;
    *plhs = mxCreateCharArray(2, odim);
    glued = (mxChar *) mxGetData(*plhs);

    /* depending on gluelen */
    gluechar = *glue;
    --ncells;
    switch (gluelen) {
        case 0:
            for (sc = 0; sc < ncells; ++sc) {
                snippet = mxGetCell(togluec, sc);
                toglue = (const mxChar*) mxGetData(snippet);
                ne = mxGetNumberOfElements(snippet);
                for (copypos = ne; copypos > 0; --copypos)
                    *glued++ = *toglue++;
            }
            break;
        case 1:
            for (sc = 0; sc < ncells; ++sc) {
                snippet = mxGetCell(togluec, sc);
                toglue = (const mxChar*) mxGetData(snippet);
                ne = mxGetNumberOfElements(snippet);
                for (copypos = ne; copypos > 0; --copypos)
                    *glued++ = *toglue++;
                *glued++ = gluechar;
            }
            break;
        case 2:
            for (sc = 0; sc < ncells; ++sc) {
                snippet = mxGetCell(togluec, sc);
                toglue = (const mxChar*) mxGetData(snippet);
                ne = mxGetNumberOfElements(snippet);
                for (copypos = ne; copypos > 0; --copypos)
                    *glued++ = *toglue++;
                *glued++ = gluechar;
                *glued++ = glue[1];
            }
            break;
        default:
            for (sc = 0; sc < ncells; ++sc) {
                snippet = mxGetCell(togluec, sc);
                toglue = (const mxChar*) mxGetData(snippet);
                ne = mxGetNumberOfElements(snippet);
                for (copypos = ne; copypos > 0; --copypos)
                    *glued++ = *toglue++;
                *glued++ = gluechar;
                for (copypos = 1; copypos < gluelen; ++copypos)
                    *glued++ = glue[copypos];
            }
            break;
    }
    snippet = mxGetCell(togluec, sc);
    ne = mxGetNumberOfElements(snippet);
    if (ne > 0) {
        toglue = (const mxChar*) mxGetData(snippet);
        for (copypos = ne; copypos > 0; --copypos)
            *glued++ = *toglue++;
    }
    if (endterm)
        for (copypos = 0; copypos < gluelen; ++copypos)
            *glued++ = *glue++;
}
Esempio n. 21
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_I = 0, IN_S, IN_END} ;
  enum {OUT_J = 0} ;
  int opt ;
  int next = IN_END ;
  mxArray const  *optarg ;

  int padding = VL_PAD_BY_CONTINUITY ;
  int kernel = GAUSSIAN ;
  int flags ;
  vl_size step = 1 ;
  int verb = 0 ;
  double sigma ;
  mxClassID classid ;

  mwSize M, N, K, M_, N_, ndims ;
  mwSize dims_ [3] ;
  mwSize const * dims ;

  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < 2) {
    mexErrMsgTxt("At least two input arguments required.");
  } else if (nout > 1) {
    mexErrMsgTxt("Too many output arguments.");
  }

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {
    switch (opt) {
      case opt_padding :
      {
        enum {buflen = 32} ;
        char buf [buflen] ;
        if (!vlmxIsString(optarg, -1)) {
          vlmxError(vlmxErrInvalidArgument,
                   "PADDING argument must be a string.") ;
        }
        mxGetString(optarg, buf, buflen) ;
        buf [buflen - 1] = 0 ;
        if (vlmxCompareStringsI("zero", buf) == 0) {
          padding = VL_PAD_BY_ZERO ;
        } else if (vlmxCompareStringsI("continuity", buf) == 0) {
          padding = VL_PAD_BY_CONTINUITY ;
        } else {
          vlmxError(vlmxErrInvalidArgument,
                   "PADDING must be either ZERO or CONTINUITY, was '%s'.",
                   buf) ;
        }
        break ;
      }

      case opt_subsample :
        if (!vlmxIsPlainScalar(optarg)) {
          vlmxError(vlmxErrInvalidArgument,
                   "SUBSAMPLE must be a scalar.") ;
        }
        step = *mxGetPr(optarg) ;
        if (step < 1) {
          vlmxError(vlmxErrInvalidArgument,
                   "SUBSAMPLE must be not less than one.") ;
        }
        break ;

      case opt_kernel :
      {
        enum {buflen = 32} ;
        char buf [buflen] ;
        if (!vlmxIsString(optarg, -1)) {
          vlmxError(vlmxErrInvalidArgument,
                   "KERNEL argument must be a string.") ;
        }
        mxGetString(optarg, buf, buflen) ;
        buf [buflen - 1] = 0 ;
        if (vlmxCompareStringsI("gaussian", buf) == 0) {
          kernel = GAUSSIAN ;
        } else if (vlmxCompareStringsI("triangular", buf) == 0) {
          kernel = TRIANGULAR ;
        } else {
          vlmxError(vlmxErrInvalidArgument,
                   "Unknown kernel type '%s'.",
                   buf) ;
        }
        break ;
      }

      case opt_verbose :
        ++ verb ;
        break ;

      default:
        abort() ;
    }
  }

  if (! vlmxIsPlainScalar(IN(S))) {
    vlmxError(vlmxErrInvalidArgument,
             "S must be a real scalar.") ;
  }

  classid = mxGetClassID(IN(I)) ;

  if (classid != mxDOUBLE_CLASS &&
      classid != mxSINGLE_CLASS) {
    vlmxError(vlmxErrInvalidArgument,
             "I must be either DOUBLE or SINGLE.") ;
  }
  if (mxGetNumberOfDimensions(IN(I)) > 3) {
    vlmxError(vlmxErrInvalidArgument,
             "I must be either a two or three dimensional array.") ;
  }

  ndims = mxGetNumberOfDimensions(IN(I)) ;
  dims = mxGetDimensions(IN(I)) ;
  M = dims[0] ;
  N = dims[1] ;
  K = (ndims > 2) ? dims[2] : 1 ;

  sigma = * mxGetPr(IN(S)) ;
  if ((sigma < 0.01) && (step == 1)) {
    OUT(J) = mxDuplicateArray(IN(I)) ;
    return ;
  }

  M_ = (M - 1) / step + 1 ;
  N_ = (N - 1) / step + 1 ;
  dims_ [0] = M_ ;
  dims_ [1] = N_ ;
  if (ndims > 2) dims_ [2] = K ;

  OUT(J) = mxCreateNumericArray(ndims, dims_, classid, mxREAL) ;

  if (verb) {
    char const *classid_str = 0, *kernel_str = 0, *padding_str = 0 ;
    switch (padding) {
      case VL_PAD_BY_ZERO       : padding_str = "with zeroes" ; break ;
      case VL_PAD_BY_CONTINUITY : padding_str = "by continuity" ; break ;
      default: abort() ;
    }
    switch (classid) {
      case mxDOUBLE_CLASS: classid_str = "DOUBLE" ; break ;
      case mxSINGLE_CLASS: classid_str = "SINGLE" ; break ;
      default: abort() ;
    }
    switch (kernel) {
      case GAUSSIAN:   kernel_str = "Gaussian" ; break ;
      case TRIANGULAR: kernel_str = "triangular" ; break ;
      default: abort() ;
    }

    mexPrintf("vl_imsmooth: [%dx%dx%d] -> [%dx%dx%d] (%s, subsampling step %d)\n",
              N, M, K, N_, M_, K, classid_str, step) ;
    mexPrintf("vl_imsmooth: padding: %s\n", padding_str) ;
    mexPrintf("vl_imsmooth: kernel: %s\n", kernel_str) ;
    mexPrintf("vl_imsmooth: sigma: %g\n", sigma) ;
    mexPrintf("vl_imsmooth: SIMD enabled: %s\n",
              vl_get_simd_enabled() ? "yes" : "no") ;
  }

  /* -----------------------------------------------------------------
   *                                                        Do the job
   * -------------------------------------------------------------- */
  flags  = padding ;
  flags |= VL_TRANSPOSE ;

  switch (classid) {
    case mxSINGLE_CLASS:
      _vl_imsmooth_smooth_f ((float*) mxGetPr(OUT(J)),
                             M_, N_,
                             (float const*) mxGetPr(IN(I)),
                             M, N, K,
                             kernel, sigma, step, flags) ;
      break ;

    case mxDOUBLE_CLASS:
      _vl_imsmooth_smooth_d ((double*) mxGetPr(OUT(J)),
                             M_, N_,
                             (double const*) mxGetPr(IN(I)),
                             M, N, K,
                             kernel, sigma, step, flags) ;
      break ;

    default:
      abort() ;
  }
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ ALLOCATES();

  CreateTicTacToc( CallMatlab );
  CreateTicTacToc( callSort   );
  int               I, J, K, ii, jj, kk;
  int               IJ, IJK, IJK_1;
  int               DI, DJ, DK, DIJK, DIJK_1;
  int               CDI, CDJ, CDK;
  int               result, fevals = 0;
  int               NVOLS, NVOLS_1, n, s, s_start, s_end, v_init;
  real              *volumes, *V, x, y, *DIST, *order, last_distance;
  int               *VV=NULL, nV, v, vv;
  char              skip;
  triplet           *TS=NULL, *DTS=NULL, T;
  mxArray           *INPUT[2]={NULL,NULL}, *OUTPUT[3]={NULL,NULL,NULL};
  double            *MAXs, LAST_MAX;
  double            thisMINx, thisMINy;
  double            *idxs;
  double            *vols;
  double            *ijk;
  char              callSort;
  mwSize            toVec[2]={1,1};
  char              VERBOSE = 0;
  char              STR[1024];
  
  
  if( nlhs > 1 ){
    mxErrMsgTxt("too much outputs");
  }


  if( mxIsChar( prhs[nrhs-1] ) ){
    mxGetString( prhs[nrhs-1], STR, 100 );
    if( ! myStrcmpi(STR,"verbose") ){ 
      VERBOSE = 1;
    } else {
      mxErrMsgTxt("only 'verbose' option allowed.");
    }
    nrhs = nrhs-1;
  }
  
  
  if( nrhs != 3 ){
    mxErrMsgTxt("sintax error. max_min_multiples_erodes( V , F , volumes )");
  }

  if( mxGetClassID( prhs[1] ) != mxFUNCTION_CLASS ){
    mxErrMsgTxt("F have to be a function_handle.");
  }

  if( myNDims( prhs[0] ) > 3  ){
    mxErrMsgTxt("bigger than 3d arrays is not allowed.");
  }
  
  NVOLS   = myNumel( prhs[2] );
  NVOLS_1 = NVOLS - 1;
  volumes = myGetPr( prhs[2] );
  
  
  I     = mySize( prhs[0] , 0 );
  J     = mySize( prhs[0] , 1 );
  K     = mySize( prhs[0] , 2 );
  IJ    = I*J;
  IJK   = IJ*K;
  

  VV = (int     *) mxMalloc( IJK*sizeof( int     ) );
  TS     = (triplet *) mxMalloc( IJK*sizeof( triplet ) );

  V = myGetPr( prhs[0] );

  v  = 0; 
  nV = 0;
  for( kk = 0 ; kk < K ; kk++ ){ for( jj = 0 ; jj < J ; jj++ ){ for( ii = 0 ; ii < I ; ii++ ){
    x = V[ v ];
    if( x == x ){
      VV[ nV ] = v;
      TS[ v ].isnan = 0;
      TS[ v ].i     = ii;
      TS[ v ].j     = jj;
      TS[ v ].k     = kk;
      nV++;
    } else {
      TS[ v ].isnan = 1;
    }
    v++;
  }}}


  INPUT[0] = prhs[1];
  INPUT[1] = mxCreateNumericMatrix( 1 , 3 , mxDOUBLE_CLASS , mxREAL );
  ijk = (double *) mxGetData( INPUT[1] );
  
  
  ijk[0] = TS[ VV[ nV/2] ].i + 1;
  ijk[1] = TS[ VV[ nV/2] ].j + 1;
  ijk[2] = TS[ VV[ nV/2] ].k + 1;
  


  OUTPUT[2] = mexCallMATLABWithTrap( 2 , OUTPUT , 2 , INPUT , "feval" );
  
  if( OUTPUT[2] == NULL ){
    
    callSort = 0;
    if( mxGetClassID( OUTPUT[0] ) != mxDOUBLE_CLASS ){
      if( INPUT[1]  != NULL ){ mxDestroyArray( INPUT[1] );  INPUT[1]=NULL;  }
      if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
      if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
      if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }
      mxErrMsgTxt("F debe retornar un double en el primer output.");
    }
    if( mxGetClassID( OUTPUT[1] ) != mxDOUBLE_CLASS ){
      if( INPUT[1]  != NULL ){ mxDestroyArray( INPUT[1] );  INPUT[1]=NULL;  }
      if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
      if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
      if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }
      mxErrMsgTxt("F debe retornar un double en el segundo output.");
    }
    
  } else {

    callSort = 1;
    if( VERBOSE ){
      mexPrintf("sort has to be called\n");
    }
    
    mxDestroyArray( OUTPUT[2] ); OUTPUT[2] = NULL;

    result = mexCallMATLAB( 1 , OUTPUT , 2 , INPUT , "feval" );
    if( result ){ mxErrMsgTxt("error computing la funcion."); }

    if( mxGetClassID( OUTPUT[0] ) != mxDOUBLE_CLASS ){
      if( INPUT[1]  != NULL ){ mxDestroyArray( INPUT[1] );  INPUT[1]=NULL;  }
      if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
      if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
      if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }
      mxErrMsgTxt("F debe retornar un double en el primer output.");
    }

  }

  DI   = mySize( OUTPUT[0] , 0 );
  DJ   = mySize( OUTPUT[0] , 1 );
  DK   = mySize( OUTPUT[0] , 2 );
  
  DTS  = (triplet *) mxMalloc( 2*DI*DJ*DK*sizeof( triplet ) );
  

  plhs[0] = mxCreateNumericMatrix( NVOLS , 1 , mxREAL_CLASS , mxREAL );
  MAXs    = (real *) mxGetData( plhs[0] );
  for( n = 0 ; n < NVOLS ; n++ ){
    MAXs[n] = -10000;
  }

  
  LAST_MAX = MAXs[ NVOLS_1 ];
  for( v_init = 0 ; v_init < EVERY ; v_init++ ){
    if( utIsInterruptPending() ){
      if( INPUT[1]  != NULL ){ mxDestroyArray( INPUT[1] );  INPUT[1]=NULL;  }
      if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
      if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
      if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }
      mexPrintf("USER INTERRUP!!!\n");
      mxErrMsgTxt("USER INTERRUP!!!");
    }
    if( VERBOSE ){
      mexPrintf("v_init:  %d  (%g)  of  %d\n", v_init , LAST_MAX , EVERY );
    }

    for( v = v_init ; v < nV ; v += EVERY ){
      vv = VV[ v ];
      
      thisMINx =   V[ vv ];
      thisMINy =  -thisMINx;
      if( ( thisMINx < LAST_MAX )  && ( thisMINy < LAST_MAX ) ){
        continue;
      }

      T = TS[ vv ];
      
      ijk[0] = T.i + 1;
      ijk[1] = T.j + 1;
      ijk[2] = T.k + 1;
      

      if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
      if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
      if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }

      if( !callSort ){
        tic( CallMatlab );
        result = mexCallMATLAB( 2 , OUTPUT , 2 , INPUT , "feval" ); fevals++;
        tac( CallMatlab );
      } else {
        tic( CallMatlab );
        result = mexCallMATLAB( 1 , OUTPUT , 2 , INPUT , "feval" ); fevals++;
        tac( CallMatlab );
      }
      
      DI   = mySize( OUTPUT[0] , 0 );
      DJ   = mySize( OUTPUT[0] , 1 );
      DK   = mySize( OUTPUT[0] , 2 );

      DIJK    = DI*DJ*DK;

      if( volumes[ NVOLS_1 ] > DIJK ){
      if( INPUT[1]  != NULL ){ mxDestroyArray( INPUT[1] );  INPUT[1]=NULL;  }
      if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
      if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
      if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }
        mxErrMsgTxt("el maximo volumen debe ser menor que numel(DIST)");
      }

      DIJK_1  = DIJK - 1;

      DIST  = (double  *) mxGetData( OUTPUT[0] );
      
      DTS  = (triplet *) mxRealloc( DTS , DIJK*sizeof( triplet ) );
      s = 0;
      for( kk = 0 ; kk < DK ; kk++ ){ for( jj = 0 ; jj < DJ ; jj++ ){ for( ii = 0 ; ii < DI ; ii++ ){
        DTS[ s ].i = ii;
        DTS[ s ].j = jj;
        DTS[ s ].k = kk;
        s++;
      }}}


      if( !callSort ){
        order = (double  *) mxGetData( OUTPUT[1] );
      } else {
        toVec[0] = mxGetNumberOfElements( OUTPUT[0] );
        mxSetDimensions( OUTPUT[0] ,  toVec  , 2 );
        
        tic( callSort );
        result = mexCallMATLAB( 2 , OUTPUT+1 , 1 , OUTPUT , "sort" );
        tac( callSort );
      
        order = (double  *) mxGetData( OUTPUT[2] );
      }
      
      CDI = DTS[ (int) ( order[0] - 1 ) ].i;
      CDJ = DTS[ (int) ( order[0] - 1 ) ].j;
      CDK = DTS[ (int) ( order[0] - 1 ) ].k;
      
      
      skip   = 0;

      s = 0;
      for( n = 0 ; n < NVOLS ; n++ ){
        s_end = (int) ( volumes[n] - 1 );
        last_distance = DIST[ (int) order[ s_end ] - 1 ];
        
        while( s_end < DIJK_1 && DIST[ (int) ( order[ s_end + 1 ] - 1 ) ] == last_distance ){
          s_end++;
        }
        s_end++;
        
        for( ; s < s_end ; s++ ){
          vv = (int) ( order[ s ] - 1 );
          
          ii = T.i + DTS[ vv ].i - CDI;  if( ii < 0 || ii > I ){ skip = 1; break; }
          jj = T.j + DTS[ vv ].j - CDJ;  if( jj < 0 || jj > J ){ skip = 1; break; }
          kk = T.k + DTS[ vv ].k - CDK;  if( kk < 0 || kk > K ){ skip = 1; break; }
            
          vv = ii + jj*I + kk*IJ;
          if( TS[ vv ].isnan ){  skip = 1; break; }
          x =  V[ vv ];  if( x < thisMINx ){ thisMINx = x; }
          y = -x;        if( y < thisMINy ){ thisMINy = y; }
          if( ( thisMINx < LAST_MAX )  && ( thisMINy < LAST_MAX ) ){
            skip = 1; break; 
          }
        }
        if( skip ){  break; }
        if( thisMINx > MAXs[n] ){ MAXs[n] = thisMINx; }
        if( thisMINy > MAXs[n] ){ MAXs[n] = thisMINy; }
      }
      LAST_MAX = MAXs[ NVOLS_1 ];

    }
    
  }
  if( INPUT[1]  != NULL ){ mxDestroyArray( INPUT[1]  ); INPUT[1] =NULL; }
  if( OUTPUT[0] != NULL ){ mxDestroyArray( OUTPUT[0] ); OUTPUT[0]=NULL; }
  if( OUTPUT[1] != NULL ){ mxDestroyArray( OUTPUT[1] ); OUTPUT[1]=NULL; }
  if( OUTPUT[2] != NULL ){ mxDestroyArray( OUTPUT[2] ); OUTPUT[2]=NULL; }
  
  if( VERBOSE ){
    mexPrintf( "\nfevals: %d  en  tiempo:   CallMatlab: %20.30g    sorting: %20.30g\n" , fevals , toc( CallMatlab ) , toc( callSort ) );
  }
  
  
  if(  VV != NULL ){  mxFree(  VV ); }
  if(  TS != NULL ){  mxFree(  TS ); }
  if( DTS != NULL ){  mxFree( DTS ); }

  myFreeALLOCATES();

}
Esempio n. 23
0
/* Gateway of LEMIRE_ENGINE */
void mexFunction(int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[]) {
    
    mxClassID ClassID;
    
    /* Data pointers, which one are used depends on the class of A */
    double *adouble, *minvaldouble, *maxvaldouble;
    float *asingle, *minvalsingle, *maxvalsingle;
    int64 *aint64, *minvalint64, *maxvalint64;
    int32 *aint32, *minvalint32, *maxvalint32;
    int16 *aint16, *minvalint16, *maxvalint16;
    int08 *aint08, *minvalint08, *maxvalint08;
    uint64 *auint64, *minvaluint64, *maxvaluint64;
    uint32 *auint32, *minvaluint32, *maxvaluint32;
    uint16 *auint16, *minvaluint16, *maxvaluint16;
    uint08 *auint08, *minvaluint08, *maxvaluint08;

    mwSize i, n, window;
    int left, size;
    mwSize *U, *L; /* wedge */
    int nU, nL; /* wedge number of elements (0 is empty wedge) */
    int Ufirst, Lfirst, Ulast, Llast; /* Indices of two ends of the wedge */
    
    /* Check number of arguments */
    if (nrhs!=2)
        mexErrMsgTxt("LEMIRE_ENGINE: two arguments are required.");
    
    /* Get class of input matrix A */
    ClassID = mxGetClassID(A);
    
    /* Do not support on sparse */
    if (mxIsSparse(A))
        mexErrMsgTxt("LEMIRE_ENGINE: First input A must be full.");       
    
    /* Get the number of elements of A */
    n = mxGetM(A)*mxGetN(A);
   
    /* Window input must be double */
    if (mxGetClassID(WINDOW)!=mxDOUBLE_CLASS)
        mexErrMsgTxt("LEMIRE_ENGINE: Second input WINDOW must be double.");
    
    /* Get the window size, cast it in mwSize */
    window = (mwSize)(*mxGetPr(WINDOW));
    
    if (window<1) /* Check if it's valid */
        mexErrMsgTxt("LEMIRE_ENGINE: windows must be 1 or greater.");   
    if (window>n || window>MAXINT)
        mexErrMsgTxt("LEMIRE_ENGINE: windows larger than data length.");
    
    /* Allocate wedges buffers for L and U, each is size (window+1) */
    size = (int)(window+1);
    L = mxMalloc((2*size)*sizeof(mwSize));
    if (L==NULL) mexErrMsgTxt("LEMIRE_ENGINE: out of memory.");
    U = L + size;
    
    /* Create output arrays */
    if (mxGetM(A)==1) /* row */
    {
        MINVAL = mxCreateNumericMatrix(1, n-window+1, ClassID, mxREAL);
        MAXVAL = mxCreateNumericMatrix(1, n-window+1, ClassID, mxREAL);
    }
    else if (mxGetN(A)==1) /* column */
    {
        MINVAL = mxCreateNumericMatrix(n-window+1, 1, ClassID, mxREAL);
        MAXVAL = mxCreateNumericMatrix(n-window+1, 1, ClassID, mxREAL);
    } else
        mexErrMsgTxt("LEMIRE_ENGINE: First input A must be a vector.");
    
    /* Check if allocation is succeeded */
    if (MINVAL==NULL || MAXVAL==NULL)
         mexErrMsgTxt("LEMIRE_ENGINE: out of memory.");   
    
    /* Initialize empty wedges L and U */
    nU = nL = 0;
    Lfirst = Ufirst = 0;
    Llast = Ulast = -1;
    
    /* Call the engine depending on ClassID */
    switch (ClassID) {
        case mxDOUBLE_CLASS:
             ENGINE(adouble, minvaldouble, maxvaldouble, double);
             break;
        case mxSINGLE_CLASS:
             ENGINE(asingle, minvalsingle, maxvalsingle, float);
             break;
        case mxINT64_CLASS:
             ENGINE(aint64, minvalint64, maxvalint64, int64);
             break;
        case mxUINT64_CLASS:
             ENGINE(auint64, minvaluint64, maxvaluint64, uint64);
             break;
        case mxINT32_CLASS:
             ENGINE(aint32, minvalint32, maxvalint32, int32);
             break;
        case mxUINT32_CLASS:
             ENGINE(auint32, minvaluint32, maxvaluint32, uint32);
             break;
        case mxCHAR_CLASS:
             ENGINE(auint16, minvaluint16, maxvaluint16, uint16);
             break;
        case mxINT16_CLASS:
             ENGINE(aint16, minvalint16, maxvalint16, int16);
             break;
        case mxUINT16_CLASS:
             ENGINE(auint16, minvaluint16, maxvaluint16, uint16);
             break;
        case mxLOGICAL_CLASS:
             ENGINE(auint08, minvaluint08, maxvaluint08, uint08);
             break;
        case mxINT8_CLASS:
             ENGINE(aint08, minvalint08, maxvalint08, int08);
             break;
        case mxUINT8_CLASS:
             ENGINE(auint08, minvaluint08, maxvaluint08, uint08);
             break;
        default:
            mexErrMsgTxt("LEMIRE_ENGINE: Class not supported.");
    } /* switch */
    
    /* Free the buffer */
    mxFree(L);
    
    return;
    
} /* Gateway LEMIRE_ENGINE */
	static inline bool CheckType(const mxArray* InputmxArray) {
		return (InputmxArray == nullptr
		        || mxIsEmpty(InputmxArray)
		        || mxGetNumberOfDimensions(InputmxArray) == 2
		           && mxGetClassID(InputmxArray) == GetMexType<typename isMexMatrix<T>::type>::typeVal);
	}
Esempio n. 25
0
/** @brief Driver.
 **
 ** @param nount number of output arguments.
 ** @param out output arguments.
 ** @param nin number of input arguments.
 ** @param in input arguments.
 **/
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum { IN_ID, IN_NEXT, IN_K, IN_X } ;
  enum { OUT_SEL } ;

  vl_uint32 const * next ;
  vl_uint32 * sel ;
  vl_uint8 const  * id ;
  vl_uint8 const  * x ;

  unsigned int K, i, N, res, last, ndims ;

  /* -----------------------------------------------------------------
   *                                                   Check arguments
   * -------------------------------------------------------------- */

  if( nin != 4 ) {
    mexErrMsgTxt("Four arguments required") ;
  } else if (nout > 1) {
    mexErrMsgTxt("At most one output argument.") ;
  }

  if(! mxIsNumeric(in[IN_NEXT])|| mxGetClassID(in[IN_NEXT])!= mxUINT32_CLASS) {
    mexErrMsgTxt("NEXT must be UINT32.") ;
  }

  if(! mxIsNumeric(in[IN_X])   || mxGetClassID(in[IN_X])!= mxUINT8_CLASS) {
    mexErrMsgTxt("X must be UINT8") ;
  }

  if (mxGetM(in[IN_NEXT]) != 1) {
    mexErrMsgTxt("NEXT must be a row vector") ;
  }

  if(! mxIsNumeric(in[IN_ID])  || mxGetClassID(in[IN_ID])!= mxUINT8_CLASS) {
    mexErrMsgTxt("ID must be UINT8.") ;
  }

  ndims = mxGetM(in[IN_ID]) ;
  res   = mxGetN(in[IN_ID]) ;

  if(res != mxGetN(in[IN_NEXT])) {
    mexErrMsgTxt("ID, NEXT must have the same number of columns") ;
  }

  if(ndims != mxGetM(in[IN_X])) {
    mexErrMsgTxt("ID and X must havethe same number of rows") ;
  }

  if(! vlmxIsPlainScalar(in[IN_K])) {
    mexErrMsgTxt("K must be a scalar") ;
  }
  K     = (unsigned int) *mxGetPr(in[IN_K]) ;

  N    = mxGetN(in[IN_X]) ;
  id   = mxGetData(in[IN_ID]) ;
  next = mxGetData(in[IN_NEXT]) ;
  x    = mxGetData(in[IN_X]) ;

  out[OUT_SEL] = mxCreateNumericMatrix
    (1, N, mxUINT32_CLASS, mxREAL) ;

  sel = mxGetData (out[OUT_SEL]) ;
  /* search for last occupied slot */
  last = res ;
  for (i = 0 ; i < res ; ++i) last = VL_MAX(last, next [i]) ;

  /* REMARK: last and next are 1 based */

  if (K > res) {
    mexErrMsgTxt("K cannot be larger then the size of H") ;
  }
  if (last > res) {
    mexErrMsgTxt("An element of NEXT is greater than the size of the table") ;
  }

  /* -----------------------------------------------------------------
   *                                                            Do job
   * -------------------------------------------------------------- */

  for (i = 0 ; i < N ; ++i) {
    /* hash */
    unsigned int h1, h2 ;
    unsigned int j, p = 0 ;

    if (is_null (x + i * ndims, ndims)) {
      *sel++ = 0 ;
      continue ;
    }

    h1 = fnv_hash(x + i * ndims, ndims) % K ;
    h2 = h1 | 0x1 ; /* this needs to be odd */

    /* search first free or matching position */
    p = h1 % K ;
    for (j = 0 ; j < K ; ++j) {
      if (is_null (id + p * ndims,                ndims) ||
          is_equal(id + p * ndims, x + i * ndims, ndims)) break ;
      h1 += h2 ;
      p = h1 % K ;
    }

    /* handle extended table */
    while (! is_null (id + p * ndims,                ndims) &&
           ! is_equal(id + p * ndims, x + i * ndims, ndims)) {
      if (next[p] == 0) break ;
      p = next [p] - 1 ;
    }

    /* found or not ? */
    if (is_equal(id + p * ndims, x + i * ndims, ndims)) {
      /* found */
      *sel++ = p + 1 ;
    } else {
      /* not found */
      *sel++ = 0 ;
    }
  } /* next guy to search for */
}
	static inline bool CheckType(const mxArray* InputmxArray) {
		return (InputmxArray == nullptr || mxIsEmpty(InputmxArray) || mxGetClassID(InputmxArray) == GetMexType<T>::typeVal);
	}
Esempio n. 27
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_I = 0, IN_END} ;
  enum {OUT_FRAMES=0, OUT_DESCRIPTORS, OUT_INFO, OUT_END} ;

  int verbose = 0 ;
  int opt ;
  int next = IN_END ;
  mxArray const *optarg ;
  VlEnumerator *pair ;

  float const *image ;
  vl_size numCols, numRows ;

  VlCovDetMethod method = VL_COVDET_METHOD_DOG;
  vl_bool estimateAffineShape = VL_FALSE ;
  vl_bool estimateOrientation = VL_FALSE ;

  vl_bool doubleImage = VL_TRUE ;
  vl_index octaveResolution = -1 ;
  double edgeThreshold = -1 ;
  double peakThreshold = -1 ;
  double lapPeakThreshold = -1 ;

  int descriptorType = -1 ;
  vl_index patchResolution = -1 ;
  double patchRelativeExtent = -1 ;
  double patchRelativeSmoothing = -1 ;
  float *patch = NULL ;
  float *patchXY = NULL ;

  vl_int liopNumSpatialBins = 6;
  vl_int liopNumNeighbours = 4;
  float liopRadius = 6.0;
  float liopIntensityThreshold = VL_NAN_F ;

  double boundaryMargin = 2.0 ;

  double * userFrames = NULL ;
  vl_size userFrameDimension = 0 ;
  vl_size numUserFrames = 0 ;

  VL_USE_MATLAB_ENV ;

  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < IN_END) {
    vlmxError(vlmxErrNotEnoughInputArguments, 0) ;
  } else if (nout > OUT_END) {
    vlmxError(vlmxErrTooManyOutputArguments, 0) ;
  }

  if (mxGetNumberOfDimensions(IN(I)) != 2 ||
      mxGetClassID(IN(I)) != mxSINGLE_CLASS){
    vlmxError(vlmxErrInvalidArgument, "I must be a matrix of class SINGLE.") ;
  }

  image = (float*) mxGetData(IN(I)) ;
  numRows = mxGetM(IN(I)) ;
  numCols = mxGetN(IN(I)) ;

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {

    switch (opt) {

    case opt_verbose :
      ++ verbose ;
      break ;

    case opt_method:
      pair = vlmxDecodeEnumeration(optarg, vlCovdetMethods, VL_TRUE) ;
      if (pair == NULL) {
        vlmxError(vlmxErrInvalidArgument, "METHOD is not a supported detection method.") ;
      }
      method = (VlCovDetMethod)pair->value ;
      break;

      case opt_descriptor:
        pair = vlmxDecodeEnumeration(optarg, vlCovDetDescriptorTypes, VL_TRUE) ;
        if (pair == NULL) {
          vlmxError(vlmxErrInvalidArgument, "DESCRIPTOR is not a supported descriptor.") ;
        }
        descriptorType = (VlCovDetDescriptorType)pair->value ;
        break;

    case opt_estimate_affine_shape:
      if (!mxIsLogicalScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "ESTIMATEAFFINESHAPE must be a logical scalar value.") ;
      } else {
        estimateAffineShape = *mxGetLogicals(optarg) ;
      }
      break ;

    case opt_estimate_orientation:
      if (!mxIsLogicalScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "ESTIMATEORIENTATION must be a logical scalar value.") ;
      } else {
        estimateOrientation = *mxGetLogicals(optarg);
      }
      break ;

    case opt_double_image:
      if (!mxIsLogicalScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "DOUBLEIMAGE must be a logical scalar value.") ;
      } else {
        doubleImage = *mxGetLogicals(optarg);
      }
      break ;

    case opt_octave_resolution :
      if (!vlmxIsPlainScalar(optarg) || (octaveResolution = (vl_index)*mxGetPr(optarg)) < 1) {
        vlmxError(vlmxErrInvalidArgument, "OCTAVERESOLUTION must be an integer not smaller than 1.") ;
      }
      break ;

    case opt_edge_threshold :
      if (!vlmxIsPlainScalar(optarg) || (edgeThreshold = *mxGetPr(optarg)) < 1) {
        vlmxError(vlmxErrInvalidArgument, "EDGETHRESHOLD must be a real not smaller than 1.") ;
      }
      break ;

    case opt_peak_threshold :
      if (!vlmxIsPlainScalar(optarg) || (peakThreshold = *mxGetPr(optarg)) < 0) {
        vlmxError(vlmxErrInvalidArgument, "PEAKTHRESHOLD must be a non-negative real.") ;
      }
      break ;
        
    case opt_laplacian_peak_threshold :
      if (!vlmxIsPlainScalar(optarg) || (lapPeakThreshold = *mxGetPr(optarg)) < 0) {
        vlmxError(vlmxErrInvalidArgument, "LAPLACIANPEAKTHRESHOLD must be a non-negative real.") ;
      }
      break ;

    case opt_patch_relative_smoothing :
      if (!vlmxIsPlainScalar(optarg) || (patchRelativeSmoothing = *mxGetPr(optarg)) < 0) {
        vlmxError(vlmxErrInvalidArgument, "PATCHRELATIVESMOOTHING must be a non-negative real.") ;
      }
      break ;

    case opt_patch_relative_extent :
      if (!vlmxIsPlainScalar(optarg) || (patchRelativeExtent = *mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "PATCHRELATIVEEXTENT must be a posiive real.") ;
      }
      break ;

    case opt_patch_resolution :
      if (!vlmxIsPlainScalar(optarg) || (patchResolution = (vl_index)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "PATCHRESOLUTION must be a positive integer.") ;
      }
      break ;

    case opt_liop_bins :
      if (!vlmxIsPlainScalar(optarg) || (liopNumSpatialBins = (vl_int)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "number of LIOPNUMSPATIALBINS is not a positive scalar.") ;
      }
      break ;

    case opt_liop_neighbours :
      if (!vlmxIsPlainScalar(optarg) || (liopNumNeighbours = (vl_int)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "number of LIOPNUMNEIGHBOURS is not a positive scalar.") ;
      }
      break ;

    case opt_liop_radius :
      if (!vlmxIsPlainScalar(optarg) || (liopRadius = (float)*mxGetPr(optarg)) <= 0) {
        vlmxError(vlmxErrInvalidArgument, "LIOPRADIUS must is not a positive scalar.") ;
      }
      break ;

    case opt_liop_threshold :
      if (!vlmxIsPlainScalar(optarg)) {
        vlmxError(vlmxErrInvalidArgument, "LIOPINTENSITYTHRESHOLD is not a scalar.") ;
      }
      liopIntensityThreshold = *mxGetPr(optarg) ;
      break ;

    case opt_frames:
      if (!vlmxIsPlainMatrix(optarg,-1,-1)) {
        vlmxError(vlmxErrInvalidArgument, "FRAMES must be a palin matrix.") ;
      }
      numUserFrames = mxGetN (optarg) ;
      userFrameDimension = mxGetM (optarg) ;
      userFrames = mxGetPr (optarg) ;
      switch (userFrameDimension) {
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
            /* ok */
          break ;
        default:
          vlmxError(vlmxErrInvalidArgument,
                    "FRAMES of dimensions %d are not recognised",
                    userFrameDimension); ;
      }
      break ;

    default :
      abort() ;
    }
  }

  if (descriptorType < 0) descriptorType = VL_COVDET_DESC_SIFT ;

  switch (descriptorType) {
    case VL_COVDET_DESC_NONE :
      break ;

    case VL_COVDET_DESC_PATCH :
      if (patchResolution < 0)  patchResolution = 20 ;
      if (patchRelativeExtent < 0) patchRelativeExtent = 6 ;
      if (patchRelativeSmoothing < 0) patchRelativeSmoothing = 1 ;
      break ;

    case VL_COVDET_DESC_SIFT :
      /* the patch parameters are selected to match the SIFT descriptor geometry */
      if (patchResolution < 0)  patchResolution = 15 ;
      if (patchRelativeExtent < 0) patchRelativeExtent = 7.5 ;
      if (patchRelativeSmoothing < 0) patchRelativeSmoothing = 1 ;
      break ;

    case VL_COVDET_DESC_LIOP :
      if (patchResolution < 0)  patchResolution = 20 ;
      if (patchRelativeExtent < 0) patchRelativeExtent = 4 ;
      if (patchRelativeSmoothing < 0) patchRelativeSmoothing = 0.5 ;
      break ;
  }

  if (patchResolution > 0) {
    vl_size w = 2*patchResolution + 1 ;
    patch = mxMalloc(sizeof(float) * w * w);
    patchXY = mxMalloc(2 * sizeof(float) * w * w);
  }

  if (descriptorType == VL_COVDET_DESC_LIOP && liopRadius > patchResolution) {
    vlmxError(vlmxErrInconsistentData, "LIOPRADIUS is larger than PATCHRESOLUTION.") ;
  }

  /* -----------------------------------------------------------------
   *                                                          Detector
   * -------------------------------------------------------------- */
  {
    VlCovDet * covdet = vl_covdet_new(method) ;

    /* set covdet parameters */
    vl_covdet_set_transposed(covdet, VL_TRUE) ;
    vl_covdet_set_first_octave(covdet, doubleImage ? -1 : 0) ;
    if (octaveResolution >= 0) vl_covdet_set_octave_resolution(covdet, octaveResolution) ;
    if (peakThreshold >= 0) vl_covdet_set_peak_threshold(covdet, peakThreshold) ;
    if (edgeThreshold >= 0) vl_covdet_set_edge_threshold(covdet, edgeThreshold) ;
    if (lapPeakThreshold >= 0) vl_covdet_set_laplacian_peak_threshold(covdet, lapPeakThreshold) ;
    
    if (verbose) {
      VL_PRINTF("vl_covdet: doubling image: %s\n",
                VL_YESNO(vl_covdet_get_first_octave(covdet) < 0)) ;
    }

    /* process the image */
    vl_covdet_put_image(covdet, image, numRows, numCols) ;

    /* fill with frames: eitehr run the detector of poure them in */
    if (numUserFrames > 0) {
      vl_index k ;

      if (verbose) {
        mexPrintf("vl_covdet: sourcing %d frames\n", numUserFrames) ;
      }

      for (k = 0 ; k < (signed)numUserFrames ; ++k) {
        double const * uframe = userFrames + userFrameDimension * k ;
        double a11, a21, a12, a22 ;
        VlCovDetFeature feature ;
        feature.peakScore = VL_INFINITY_F ;
        feature.edgeScore = 1.0 ;
        feature.frame.x = (float)uframe[1] - 1 ;
        feature.frame.y = (float)uframe[0] - 1 ;

        switch (userFrameDimension) {
          case 2:
            a11 = 1.0 ;
            a21 = 0.0 ;
            a12 = 0.0 ;
            a22 = 1.0 ;
            break ;
          case 3:
            a11 = uframe[2] ;
            a21 = 0.0 ;
            a12 = 0.0 ;
            a22 = uframe[2] ;
            break ;
          case 4:
          {
            double sigma = uframe[2] ;
            double c = cos(uframe[3]) ;
            double s = sin(uframe[3]) ;
            a11 = sigma * c ;
            a21 = sigma * s ;
            a12 = sigma * (-s) ;
            a22 = sigma * c ;
            break ;
          }
          case 5:
          {
            double d2 ;
            if (uframe[2] < 0) {
              vlmxError(vlmxErrInvalidArgument, "FRAMES(:,%d) does not have a PSD covariance.", k+1) ;
            }
            a11 = sqrt(uframe[2]) ;
            a21 = uframe[3] / VL_MAX(a11, 1e-10) ;
            a12 = 0.0 ;
            d2 = uframe[4] - a21*a21 ;
            if (d2 < 0) {
              vlmxError(vlmxErrInvalidArgument, "FRAMES(:,%d) does not have a PSD covariance.", k+1) ;
            }
            a22 = sqrt(d2) ;
            break ;
          }
          case 6:
          {
            a11 = uframe[2] ;
            a21 = uframe[3] ;
            a12 = uframe[4] ;
            a22 = uframe[5] ;
            break ;
          }
          default:
            a11 = 0 ;
            a21 = 0 ;
            a12 = 0 ;
            a22 = 0 ;
            assert(0) ;
        }
        feature.frame.a11 = (float)a22 ;
        feature.frame.a21 = (float)a12 ;
        feature.frame.a12 = (float)a21 ;
        feature.frame.a22 = (float)a11 ;
        vl_covdet_append_feature(covdet, &feature) ;
      }
    } else {
      if (verbose) {
        mexPrintf("vl_covdet: detector: %s\n",
                  vl_enumeration_get_by_value(vlCovdetMethods, method)->name) ;
        mexPrintf("vl_covdet: peak threshold: %g, edge threshold: %g\n",
                  vl_covdet_get_peak_threshold(covdet),
                  vl_covdet_get_edge_threshold(covdet)) ;
      }

      vl_covdet_detect(covdet) ;

      if (verbose) {
        vl_index i ;
        vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
        mexPrintf("vl_covdet: %d features suppressed as duplicate (threshold: %g)\n",
                  vl_covdet_get_num_non_extrema_suppressed(covdet),
                  vl_covdet_get_non_extrema_suppression_threshold(covdet)) ;
        switch (method) {
        case VL_COVDET_METHOD_HARRIS_LAPLACE:
        case VL_COVDET_METHOD_HESSIAN_LAPLACE:
          {
            vl_size numScales ;
            vl_size const * numFeaturesPerScale ;
            numFeaturesPerScale = vl_covdet_get_laplacian_scales_statistics
              (covdet, &numScales) ;
            mexPrintf("vl_covdet: Laplacian scales:") ;
            for (i = 0 ; i <= (signed)numScales ; ++i) {
              mexPrintf("%d with %d scales;", numFeaturesPerScale[i], i) ;
            }
            mexPrintf("\n") ;
          }
          break ;
        default:
          break ;
        }
        mexPrintf("vl_covdet: detected %d features\n", numFeatures) ;
      }

      if (boundaryMargin > 0) {
        vl_covdet_drop_features_outside (covdet, boundaryMargin) ;
        if (verbose) {
          vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
          mexPrintf("vl_covdet: kept %d inside the boundary margin (%g)\n",
                    numFeatures, boundaryMargin) ;
        }
      }
    }

    /* affine adaptation if needed */
    if (estimateAffineShape) {
      if (verbose) {
        vl_size numFeaturesBefore = vl_covdet_get_num_features(covdet) ;
        mexPrintf("vl_covdet: estimating affine shape for %d features\n", numFeaturesBefore) ;
      }

      vl_covdet_extract_affine_shape(covdet) ;

      if (verbose) {
        vl_size numFeaturesAfter = vl_covdet_get_num_features(covdet) ;
        mexPrintf("vl_covdet: %d features passed affine adaptation\n", numFeaturesAfter) ;
      }
    }

    /* orientation estimation if needed */
    if (estimateOrientation) {
      vl_size numFeaturesBefore = vl_covdet_get_num_features(covdet) ;
      vl_size numFeaturesAfter ;

      vl_covdet_extract_orientations(covdet) ;

      numFeaturesAfter = vl_covdet_get_num_features(covdet) ;
      if (verbose && numFeaturesAfter > numFeaturesBefore) {
        mexPrintf("vl_covdet: %d duplicate features were crated due to ambiguous "
                  "orientation detection (%d total)\n",
                  numFeaturesAfter - numFeaturesBefore, numFeaturesAfter) ;
      }
    }

    /* store results back */
    {
      vl_index i  ;
      vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
      VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
      double * pt ;

      OUT(FRAMES) = mxCreateDoubleMatrix (6, numFeatures, mxREAL) ;
      pt = mxGetPr(OUT(FRAMES)) ;

      for (i = 0 ; i < (signed)numFeatures ; ++i) {
        /* save the transposed frame, adjust origin to MATLAB's*/
        *pt++ = feature[i].frame.y + 1 ;
        *pt++ = feature[i].frame.x + 1 ;
        *pt++ = feature[i].frame.a22 ;
        *pt++ = feature[i].frame.a12 ;
        *pt++ = feature[i].frame.a21 ;
        *pt++ = feature[i].frame.a11 ;
      }
    }

    if (nout >= 2) {
      switch (descriptorType) {
        case VL_COVDET_DESC_NONE:
          OUT(DESCRIPTORS) = mxCreateDoubleMatrix(0,0,mxREAL);
          break ;

        case VL_COVDET_DESC_PATCH:
        {
		  vl_size numFeatures ;
		  VlCovDetFeature const * feature ;
          vl_index i ;
          vl_size w = 2*patchResolution + 1 ;
          float * desc ;

          if (verbose) {
            mexPrintf("vl_covdet: descriptors: type=patch, "
                      "resolution=%d, extent=%g, smoothing=%g\n",
                      patchResolution, patchRelativeExtent,
                      patchRelativeSmoothing);
          }
          numFeatures = vl_covdet_get_num_features(covdet) ;
          feature = vl_covdet_get_features(covdet);
          OUT(DESCRIPTORS) = mxCreateNumericMatrix(w*w, numFeatures, mxSINGLE_CLASS, mxREAL) ;
          desc = mxGetData(OUT(DESCRIPTORS)) ;
          for (i = 0 ; i < (signed)numFeatures ; ++i) {
            vl_covdet_extract_patch_for_frame(covdet,
                                    desc,
                                    patchResolution,
                                    patchRelativeExtent,
                                    patchRelativeSmoothing,
                                    feature[i].frame) ;
            desc += w*w ;
          }
          break ;
        }
        case VL_COVDET_DESC_SIFT:
        {
          vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
          VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
          VlSiftFilt * sift = vl_sift_new(16, 16, 1, 3, 0) ;
          vl_index i ;
          vl_size dimension = 128 ;
          vl_size patchSide = 2 * patchResolution + 1 ;
          double patchStep = (double)patchRelativeExtent / patchResolution ;
          float tempDesc [128] ;
          float * desc ;
          if (verbose) {
            mexPrintf("vl_covdet: descriptors: type=sift, "
                      "resolution=%d, extent=%g, smoothing=%g\n",
                      patchResolution, patchRelativeExtent,
                      patchRelativeSmoothing);
          }
          OUT(DESCRIPTORS) = mxCreateNumericMatrix(dimension, numFeatures, mxSINGLE_CLASS, mxREAL) ;
          desc = mxGetData(OUT(DESCRIPTORS)) ;
          vl_sift_set_magnif(sift, 3.0) ;
          for (i = 0 ; i < (signed)numFeatures ; ++i) {
            vl_covdet_extract_patch_for_frame(covdet,
                                              patch,
                                              patchResolution,
                                              patchRelativeExtent,
                                              patchRelativeSmoothing,
                                              feature[i].frame) ;

            vl_imgradient_polar_f (patchXY, patchXY +1,
                                   2, 2 * patchSide,
                                   patch, patchSide, patchSide, patchSide) ;


            /*
             Note: the patch is transposed, so that x and y are swapped.
             However, if NBO is not divisible by 4, then the configuration
             of the SIFT orientations is not symmetric by rotations of pi/2.
             Hence the only option is to rotate the descriptor further by
             an angle we need to compute the descriptor rotaed by an additional pi/2
             angle. In this manner, x concides and y is flipped.
             */
            vl_sift_calc_raw_descriptor (sift,
                                         patchXY,
                                         tempDesc,
                                         (int)patchSide, (int)patchSide,
                                         (double)(patchSide-1) / 2, (double)(patchSide-1) / 2,
                                         (double)patchRelativeExtent / (3.0 * (4 + 1) / 2) /
                                         patchStep,
                                         VL_PI / 2) ;

            flip_descriptor (desc, tempDesc) ;
            desc += dimension ;
          }
          vl_sift_delete(sift) ;
          break ;
        }
        case VL_COVDET_DESC_LIOP :
        {          /* TODO: get parameters form input */
          vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
          vl_size dimension ;
          VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
          vl_index i ;

          vl_size patchSide = 2 * patchResolution + 1 ;
          float * desc ;

          VlLiopDesc * liop = vl_liopdesc_new(liopNumNeighbours, liopNumSpatialBins, liopRadius, (vl_size)patchSide) ;
          if (!vl_is_nan_f(liopIntensityThreshold)) {
            vl_liopdesc_set_intensity_threshold(liop, liopIntensityThreshold) ;
          }
          dimension = vl_liopdesc_get_dimension(liop) ;
          if (verbose) {
            mexPrintf("vl_covdet: descriptors: type=liop, "
                      "resolution=%d, extent=%g, smoothing=%g\n",
                      patchResolution, patchRelativeExtent,
                      patchRelativeSmoothing);
          }
          OUT(DESCRIPTORS) = mxCreateNumericMatrix(dimension, numFeatures, mxSINGLE_CLASS, mxREAL);
          desc = mxGetData(OUT(DESCRIPTORS)) ;
          vl_tic();
          for(i = 0; i < (signed)numFeatures; i++){
              vl_covdet_extract_patch_for_frame(covdet,
                                                patch,
                                                patchResolution,
                                                patchRelativeExtent,
                                                patchRelativeSmoothing,
                                                feature[i].frame);

              vl_liopdesc_process(liop, desc, patch);

              desc += dimension;

          }
          mexPrintf("time: %f\n",vl_toc());
          mexPrintf("threshold: %f\n",liop->intensityThreshold);
          break;
        }

        default:
          assert(0) ; /* descriptor type */
      }
    }

    if (nout >= 3) {
      vl_index i ;
      vl_size numFeatures = vl_covdet_get_num_features(covdet) ;
      VlCovDetFeature const * feature = vl_covdet_get_features(covdet);
      const char* names[] = {
        "gss",
        "css",
        "peakScores",
        "edgeScores",
        "orientationScore",
        "laplacianScaleScore"
      };
      mxArray * gss_array = _createArrayFromScaleSpace(vl_covdet_get_gss(covdet)) ;
      mxArray * css_array = _createArrayFromScaleSpace(vl_covdet_get_css(covdet)) ;
      mxArray * peak_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;
      mxArray * edge_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;
      mxArray * orientation_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;
      mxArray * laplacian_array = mxCreateNumericMatrix(1,numFeatures,mxSINGLE_CLASS,mxREAL) ;

      float * peak = mxGetData(peak_array) ;
      float * edge = mxGetData(edge_array) ;
      float * orientation = mxGetData(orientation_array) ;
      float * laplacian = mxGetData(laplacian_array) ;
      for (i = 0 ; i < (signed)numFeatures ; ++i) {
        peak[i] = feature[i].peakScore ;
        edge[i] = feature[i].edgeScore ;
        orientation[i] = feature[i].orientationScore ;
        laplacian[i] = feature[i].laplacianScaleScore ;
      }

      OUT(INFO) = mxCreateStructMatrix(1, 1, 6, names) ;
      mxSetFieldByNumber(OUT(INFO), 0, 0, gss_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 1, css_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 2, peak_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 3, edge_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 4, orientation_array) ;
      mxSetFieldByNumber(OUT(INFO), 0, 5, laplacian_array) ;
    }
    /* cleanup */
    vl_covdet_delete (covdet) ;
  }

  if (patchXY) mxFree(patchXY) ;
  if (patch) mxFree(patch) ;
}
Esempio n. 28
0
void mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{


    mwIndex i,j, jwalk, ccI, *buffer, *bfr, bufferI;
    mwSize n,m,gsize,t;
    uint32_T *A, *cI, *sizes,*sizesp;;
      

    if (nrhs >1) 
        mexErrMsgTxt("Wrong number of input arguments");
    if ((nlhs > 3))
        mexErrMsgTxt("Wrong number of output arguments");
    
    n = mxGetN(A_IN);
    m = mxGetM(A_IN);
    if ((m!=1) && (n!=1))
        mexErrMsgTxt("Input must be a vector");
    if (mxGetClassID(A_IN) != mxUINT32_CLASS)
        mexErrMsgTxt("Input vector must be of type uint32");
    A = (uint32_T *) mxGetPr(A_IN);
    if (m>n)
        n=m;
     
    
    /* Create output */
    cI_OUT = mxCreateNumericMatrix(n, 1, mxUINT32_CLASS, mxREAL);
    if (cI_OUT == NULL) 
         mexErrMsgTxt("Unsufficient memory");
    cI = (uint32_T *) mxGetPr(cI_OUT);
    for (j=1 ;j<n ;j++)
        cI[j]=0;
    
    t = 1; 
    gsize = 100;
    buffer = mxMalloc(gsize*sizeof(mwIndex));
    if (nlhs == 3){
      sizes = mxMalloc(n*sizeof(double));
      for (j=1 ;j<n ;j++)
          sizes[j]=0.0;
    }

    if (nlhs <3 ){  /* sizes are not recorded */
    ccI = 1;
    for (j=0 ; j<n ; j++){
        bufferI=0;
        jwalk = j;
        /* Tree walk */
        while (cI[jwalk]==0 && A[j]!=(n+1)){
            if (bufferI==t*gsize) {
                t = t+1;
                bfr = mxRealloc(buffer,t*gsize*sizeof(mwIndex));
                buffer = bfr;
            }
            cI[jwalk] = ccI;
            buffer[bufferI] = jwalk; 
            bufferI = bufferI+1;
            jwalk = A[jwalk];}
        if (cI[jwalk] != ccI)
            for (i=0; i<bufferI; i++)
                cI[buffer[i]] = cI[jwalk];
        else
            ccI = ccI+1;
    }}

    if (nlhs == 3 ){  /* sizes are recorded */
    ccI = 1;
    for (j=0 ; j<n ; j++){
        bufferI=0;
        jwalk = j;
        /* Tree walk */
        while (cI[jwalk]==0 && A[j]!=(n+1)){
            if (bufferI==t*gsize) {
                t = t+1;
                bfr = mxRealloc(buffer,t*gsize*sizeof(mwIndex));
                buffer = bfr;
            }
            cI[jwalk] = ccI;
            buffer[bufferI] = jwalk; 
            bufferI = bufferI+1;
            jwalk = A[jwalk];}
        if (cI[jwalk] != ccI){
            for (i=0; i<bufferI; i++)
                cI[buffer[i]] = cI[jwalk];}
        else
            ccI = ccI+1;
        sizes[(mwIndex) cI[jwalk]-1] = sizes[(mwIndex) cI[jwalk]-1] + (double) bufferI;
    }}

    ccI = ccI-1;
    nc_OUT = mxCreateDoubleScalar(ccI);
    
    if (nlhs == 3) {
        sizes_OUT = mxCreateDoubleMatrix(1,ccI,mxREAL);
        sizesp = (uint32_T *) mxGetPr(sizes_OUT);
        for (j=0 ; j<ccI; j++) 
            sizesp[j] = sizes[j];
        mxFree(sizes);
    }
    
    mxFree(buffer);

}    
Esempio n. 29
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) {
    double *Dxx, *Dxy, *Dxz, *Dyy, *Dyz, *Dzz;
    double *Dvecx, *Dvecy, *Dvecz, *Deiga, *Deigb, *Deigc;

    float *Dxx_f, *Dxy_f, *Dxz_f, *Dyy_f, *Dyz_f, *Dzz_f;
    float *Dvecx_f, *Dvecy_f, *Dvecz_f, *Deiga_f, *Deigb_f, *Deigc_f;

    mwSize output_dims[2]={1, 3};
    double Ma[3][3];
    double Davec[3][3];
    double Daeig[3];
    
    /* Loop variable */
    int i;
    
    /* Size of input */
    const mwSize *idims;
    int nsubs=0;
    
    /* Number of pixels */
    int npixels=1;
    
    /* Check for proper number of arguments. */
    if(nrhs!=6) {
        mexErrMsgTxt("Six inputs are required.");
    } else if(nlhs<3) {
        mexErrMsgTxt("Three or Six outputs are required");
    }
    
   
    /*  Get the number of dimensions */
    nsubs = mxGetNumberOfDimensions(prhs[0]);
    /* Get the sizes of the inputs */
    idims = mxGetDimensions(prhs[0]);
    for (i=0; i<nsubs; i++) { npixels=npixels*idims[i]; }
    
    if(mxGetClassID(prhs[0])==mxDOUBLE_CLASS) {
       /* Assign pointers to each input. */
        Dxx = (double *)mxGetPr(prhs[0]);
        Dxy = (double *)mxGetPr(prhs[1]);
        Dxz = (double *)mxGetPr(prhs[2]);
        Dyy = (double *)mxGetPr(prhs[3]);
        Dyz = (double *)mxGetPr(prhs[4]);
        Dzz = (double *)mxGetPr(prhs[5]);

        /* Assign pointers to each output. */
        plhs[0] = mxCreateNumericArray(nsubs, idims, mxDOUBLE_CLASS, mxREAL);
        plhs[1] = mxCreateNumericArray(nsubs, idims, mxDOUBLE_CLASS, mxREAL);
        plhs[2] = mxCreateNumericArray(nsubs, idims, mxDOUBLE_CLASS, mxREAL);
        Deiga = mxGetPr(plhs[0]); Deigb = mxGetPr(plhs[1]); Deigc = mxGetPr(plhs[2]);
        if(nlhs==6) {
            /* Main direction (larged eigenvector) */
            plhs[3] = mxCreateNumericArray(nsubs, idims, mxDOUBLE_CLASS, mxREAL);
            plhs[4] = mxCreateNumericArray(nsubs, idims, mxDOUBLE_CLASS, mxREAL);
            plhs[5] = mxCreateNumericArray(nsubs, idims, mxDOUBLE_CLASS, mxREAL);
            Dvecx = mxGetPr(plhs[3]); Dvecy = mxGetPr(plhs[4]); Dvecz = mxGetPr(plhs[5]);
        }
        
        
        for(i=0; i<npixels; i++) {
            Ma[0][0]=Dxx[i]; Ma[0][1]=Dxy[i]; Ma[0][2]=Dxz[i];
            Ma[1][0]=Dxy[i]; Ma[1][1]=Dyy[i]; Ma[1][2]=Dyz[i];
            Ma[2][0]=Dxz[i]; Ma[2][1]=Dyz[i]; Ma[2][2]=Dzz[i];
            eigen_decomposition(Ma, Davec, Daeig);
            Deiga[i]=Daeig[0]; Deigb[i]=Daeig[1]; Deigc[i]=Daeig[2];
            if(nlhs==6) {
                /* Main direction (smallest eigenvector) */
                Dvecx[i]=Davec[0][0];
                Dvecy[i]=Davec[1][0];
                Dvecz[i]=Davec[2][0];
            }
        }
    }
    else if(mxGetClassID(prhs[0])==mxSINGLE_CLASS) {
       /* Assign pointers to each input. */
        Dxx_f = (float *)mxGetPr(prhs[0]);
        Dxy_f = (float *)mxGetPr(prhs[1]);
        Dxz_f = (float *)mxGetPr(prhs[2]);
        Dyy_f = (float *)mxGetPr(prhs[3]);
        Dyz_f = (float *)mxGetPr(prhs[4]);
        Dzz_f = (float *)mxGetPr(prhs[5]);

        /* Assign pointers to each output. */
        plhs[0] = mxCreateNumericArray(nsubs, idims, mxSINGLE_CLASS, mxREAL);
        plhs[1] = mxCreateNumericArray(nsubs, idims, mxSINGLE_CLASS, mxREAL);
        plhs[2] = mxCreateNumericArray(nsubs, idims, mxSINGLE_CLASS, mxREAL);
        Deiga_f  = (float *)mxGetPr(plhs[0]); 
        Deigb_f  = (float *)mxGetPr(plhs[1]); 
        Deigc_f  = (float *)mxGetPr(plhs[2]);
        if(nlhs==6) {
            /* Main direction (smallest eigenvector) */
            plhs[3] = mxCreateNumericArray(nsubs, idims, mxSINGLE_CLASS, mxREAL);
            plhs[4] = mxCreateNumericArray(nsubs, idims, mxSINGLE_CLASS, mxREAL);
            plhs[5] = mxCreateNumericArray(nsubs, idims, mxSINGLE_CLASS, mxREAL);
            Dvecx_f  = (float *)mxGetPr(plhs[3]); 
            Dvecy_f  = (float *)mxGetPr(plhs[4]); 
            Dvecz_f  = (float *)mxGetPr(plhs[5]);
        }
        
        
        for(i=0; i<npixels; i++) {
            Ma[0][0]=(double)Dxx_f[i]; Ma[0][1]=(double)Dxy_f[i]; Ma[0][2]=(double)Dxz_f[i];
            Ma[1][0]=(double)Dxy_f[i]; Ma[1][1]=(double)Dyy_f[i]; Ma[1][2]=(double)Dyz_f[i];
            Ma[2][0]=(double)Dxz_f[i]; Ma[2][1]=(double)Dyz_f[i]; Ma[2][2]=(double)Dzz_f[i];
            eigen_decomposition(Ma, Davec, Daeig);
            Deiga_f[i]=(float)Daeig[0]; 
            Deigb_f[i]=(float)Daeig[1]; 
            Deigc_f[i]=(float)Daeig[2];
            if(nlhs==6) {
                /* Main direction (smallest eigenvector) */
                Dvecx_f[i]=(float)Davec[0][0]; 
                Dvecy_f[i]=(float)Davec[1][0]; 
                Dvecz_f[i]=(float)Davec[2][0];
            }
        }

    }
}
Esempio n. 30
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  const mxArray *srcmat;
  int ndim, *dimsize, eltsize;
  const int *dims;
  int ndimdest, *destdims, *destdimsize;
  char *src, *dest;
  int *rep;
  int i,nrep;
  int extra_rep = 1;
  int empty;

  if(nrhs < 2) mexErrMsgTxt("Usage: xrepmat(A, [N M ...])");
  srcmat = prhs[0];
  if(mxIsSparse(srcmat)) {
    mexErrMsgTxt("Sorry, can't handle sparse matrices yet.");
  }
  if(mxIsCell(srcmat)) {
    mexErrMsgTxt("Sorry, can't handle cell arrays yet.");
  }
  ndim = mxGetNumberOfDimensions(srcmat);
  dims = mxGetDimensions(srcmat);
  eltsize = mxGetElementSize(srcmat);

  /* compute dimension sizes */
  dimsize = mxCalloc(ndim, sizeof(int));
  dimsize[0] = eltsize*dims[0];
  for(i=1;i<ndim;i++) dimsize[i] = dimsize[i-1]*dims[i];

  /* determine repetition vector */
  ndimdest = ndim;
  if(nrhs == 2) {
    nrep = mxGetN(prhs[1]);
    if(nrep > ndimdest) ndimdest = nrep;
    rep = mxCalloc(ndimdest, sizeof(int));
    for(i=0;i<nrep;i++) {
      double repv = mxGetPr(prhs[1])[i];
      rep[i] = (int)repv;
    }
    if(nrep == 1) {
      /* special behavior */
      nrep = 2;
      rep[1] = rep[0];
    }
  }
  else {
    nrep = nrhs-1;
    if(nrep > ndimdest) ndimdest = nrep;
    rep = mxCalloc(ndimdest, sizeof(int));
    for(i=0;i<nrep;i++) {
      rep[i] = (int)*mxGetPr(prhs[i+1]);
    }
  }
  for(i=nrep;i<ndimdest;i++) rep[i] = 1;

  /* compute output size */
  destdims = mxCalloc(ndimdest, sizeof(int));
  for(i=0;i<ndim;i++) destdims[i] = dims[i]*rep[i];
  for(;i<ndimdest;i++) { 
    destdims[i] = rep[i];
    extra_rep *= rep[i];
  }
  destdimsize = mxCalloc(ndim, sizeof(int));
  destdimsize[0] = eltsize*destdims[0];
  for(i=1;i<ndim;i++) destdimsize[i] = destdimsize[i-1]*destdims[i];

    
  /* for speed, array should be uninitialized */
  plhs[0] = mxCreateNumericArray(ndimdest, destdims, mxGetClassID(srcmat), 
				  mxIsComplex(srcmat)?mxCOMPLEX:mxREAL);

  /* if any rep[i] == 0, output should be empty array.
     Added by KPM 11/13/02.
  */
  empty = 0;
  for (i=0; i < nrep; i++) {
    if (rep[i]==0) 
      empty = 1;
  }
  if (empty) 
    return;

  src = (char*)mxGetData(srcmat);
  dest = (char*)mxGetData(plhs[0]);
  repmat(dest,src,ndim,destdimsize,dimsize,dims,rep);
  if(ndimdest > ndim) memrep(dest,destdimsize[ndim-1],extra_rep);
  if(mxIsComplex(srcmat)) {
    src = (char*)mxGetPi(srcmat);
    dest = (char*)mxGetPi(plhs[0]);
    repmat(dest,src,ndim,destdimsize,dimsize,dims,rep);
    if(ndimdest > ndim) memrep(dest,destdimsize[ndim-1],extra_rep);
  }
}