Ejemplo n.º 1
0
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
  if (nrhs != 2) mexErrMsgTxt("Takes 2 input arguments");
  int N1=mxGetN(prhs[0]); int N2=mxGetN(prhs[1]);
  if (!mxIsUint32(prhs[0]) && N1>0) mexErrMsgTxt("Arguments must be sorted uint32s");
  if (!mxIsUint32(prhs[1]) && N2>0) mexErrMsgTxt("Arguments must be sorted uint32s");

  uint32_t *src, *cmp, *dest;
  src = (uint32_t *) mxGetData(prhs[0]); 
  cmp = (uint32_t *) mxGetData(prhs[1]);
  
  plhs[0] = mxCreateNumericMatrix(1,N1,mxUINT32_CLASS,mxREAL); 
  dest=(uint32_t *) mxGetData(plhs[0]);

  uint32_t* end = std::set_intersection( src, src+N1, cmp, cmp+N2, dest );
  mxSetN(plhs[0],end-dest);
/*	
  unsigned int i,j,k;
  for (i=0,j=0,k=0; i<N1 && j<N2; ) {
    if (src[i] < cmp[j]) dest[k++]=src[i++]; 
    else if (src[i]==cmp[j]) { i++; }
    else if (src[i] > cmp[j] && j<N2) j++;
  }
  while (i<N1) dest[k++]=src[i++];
  mxSetN(plhs[0],k);
*/

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check for proper number of arguments
    if (nrhs != 2)
        mexErrMsgTxt("Two input arguments required.");
    if (nlhs != 4)
        mexErrMsgTxt("Four output arguments required.");
    
    // The input must be noncomplex
    if (mxIsComplex(prhs[0]) || mxIsComplex(prhs[1]) ||
        !mxIsNumeric(prhs[0]) || !mxIsNumeric(prhs[1]))
        mexErrMsgTxt("The input must be noncomplex (and numeric).");

    // The second input must be an unsigned integer
    if (mxIsSingle(prhs[1]) || mxIsDouble(prhs[1]))
        mexErrMsgTxt("The second input must be an integer.");

    if (mxIsSingle(prhs[0])) {
        if (mxIsInt8(prhs[1]))
            compute<float, char>(plhs, prhs);
        else if (mxIsUint8(prhs[1]))
            compute<float, unsigned char>(plhs, prhs);
        else if (mxIsInt16(prhs[1]))
            compute<float, short>(plhs, prhs);
        else if (mxIsUint16(prhs[1]))
            compute<float, unsigned short>(plhs, prhs);
        else if (mxIsInt32(prhs[1]))
            compute<float, int>(plhs, prhs);
        else if (mxIsUint32(prhs[1]))
            compute<float, unsigned int>(plhs, prhs);
        else if (mxIsInt64(prhs[1]))
            compute<float, long long int>(plhs, prhs);
        else if (mxIsUint64(prhs[1]))
            compute<float, unsigned long long int>(plhs, prhs);
    }
    else if (mxIsDouble(prhs[0])) {
        if (mxIsInt8(prhs[1]))
            compute<double, char>(plhs, prhs);
        else if (mxIsUint8(prhs[1]))
            compute<double, unsigned char>(plhs, prhs);
        else if (mxIsInt16(prhs[1]))
            compute<double, short>(plhs, prhs);
        else if (mxIsUint16(prhs[1]))
            compute<double, unsigned short>(plhs, prhs);
        else if (mxIsInt32(prhs[1]))
            compute<double, int>(plhs, prhs);
        else if (mxIsUint32(prhs[1]))
            compute<double, unsigned int>(plhs, prhs);
        else if (mxIsInt64(prhs[1]))
            compute<double, long long int>(plhs, prhs);
        else if (mxIsUint64(prhs[1]))
            compute<double, unsigned long long int>(plhs, prhs);
    }
    else
        mexErrMsgTxt("Input types not supported.");
    
}
Ejemplo n.º 3
0
/**
 * @brief This file implements an interface to add a Factor to an opengm model in MatLab.
 *
 * This routine accepts a function id and a subset of variables and connects them to a new factor of the model.
 *
 * @param[in] nlhs number of output arguments expected from MatLab.
 * (needs to be 0).
 * @param[out] plhs pointer to the mxArrays containing the results.
 * @param[in] nrhs number of input arguments provided from MatLab.
 * (needs to be 3)
 * @param[in] prhs pointer to the mxArrays containing the input data provided by
 * matlab. prhs[0] needs to contain the handle for the model.
 * prhs[1] needs to contain the function id. prhs[2] needs to contain a matrix where every column represents a subset of variables.
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  //check if data is in correct format
  if(nrhs != 3) {
     mexErrMsgTxt("Wrong number of input variables specified (three needed)\n");
  }
  if(nlhs != 0) {
     mexErrMsgTxt("Wrong number of output variables specified (zero needed)\n");
  }

  // get model out of handle
  typedef opengm::interface::MatlabModelType::GmType GmType;
  GmType& gm = opengm::interface::handle<GmType>::getObject(prhs[0]);

  // get function id
  GmType::FunctionIdentifier::FunctionIndexType functionIndex;
  GmType::FunctionIdentifier::FunctionTypeIndexType functionType;

  if((mxIsUint8(prhs[1]) || mxIsUint16(prhs[1]) || mxIsUint32(prhs[1]) || mxIsUint64(prhs[1])) && (mxGetM(prhs[1]) == 1) && (mxGetN(prhs[1]) == 2)) {
     if(mxIsUint8(prhs[1])) {
        const uint8_T* data = static_cast<const uint8_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     } else if(mxIsUint16(prhs[1])) {
        const uint16_T* data = static_cast<const uint16_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     } else if(mxIsUint32(prhs[1])) {
        const uint32_T* data = static_cast<const uint32_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     } else if(mxIsUint64(prhs[1])) {
        const uint64_T* data = static_cast<const uint64_T*>(mxGetData(prhs[1]));
        functionIndex = static_cast<GmType::FunctionIdentifier::FunctionIndexType>(data[0]);
        functionType = static_cast<GmType::FunctionIdentifier::FunctionTypeIndexType>(data[1]);
     }
  } else {
     mexErrMsgTxt("Unsupported dataformat for function id!");
  }
  GmType::FunctionIdentifier functionID(functionIndex, functionType);

  // get subset of variables and add factor
  if(mxIsNumeric(prhs[2])) {
     if(mxGetNumberOfDimensions(prhs[2]) != 2) {
        mexErrMsgTxt("variables has to be a matrix where every column represents a subset of variables!");
     }
     size_t numFactors = mxGetN(prhs[2]);
     size_t numVariablesPerFactor = mxGetM(prhs[2]);
     typedef opengm::interface::helper::getDataFromMXArray<addFactorsFunctor> factorAdder;
     addFactorsFunctor functor(functionID, gm, numFactors, numVariablesPerFactor);
     factorAdder()(functor, prhs[2]);
  } else {
     mexErrMsgTxt("Unsupported dataformat for subset of variables!");
  }
}
Ejemplo n.º 4
0
int mxGetElementSize(const mxArray *ptr)
{
    if (mxIsChar(ptr))
    {
        return sizeof(wchar_t*);
    }
    else if (mxIsLogical(ptr))
    {
        return sizeof(int);
    }
    else if (mxIsDouble(ptr))
    {
        return sizeof(double);
    }
    else if (mxIsSparse(ptr))
    {
        return sizeof(double);
    }
    else if (mxIsInt8(ptr))
    {
        return sizeof(char);
    }
    else if (mxIsInt16(ptr))
    {
        return sizeof(short);
    }
    else if (mxIsInt32(ptr))
    {
        return sizeof(int);
    }
    else if (mxIsInt64(ptr))
    {
        return sizeof(long long);
    }
    else if (mxIsUint8(ptr))
    {
        return sizeof(unsigned char);
    }
    else if (mxIsUint16(ptr))
    {
        return sizeof(unsigned short);
    }
    else if (mxIsUint32(ptr))
    {
        return sizeof(unsigned int);
    }
    else if (mxIsUint64(ptr))
    {
        return sizeof(unsigned long long);
    }
    else if (mxIsCell(ptr))
    {
        return sizeof(types::InternalType*);
    }
    else if (mxIsStruct(ptr))
    {
        return sizeof(types::SingleStruct*);
    }
    return 0;
}
Ejemplo n.º 5
0
const char *mxGetClassName(const mxArray *ptr)
{
    if (mxIsDouble(ptr))
    {
        return "double";
    }
    if (mxIsChar(ptr))
    {
        return "char";
    }
    if (mxIsLogical(ptr))
    {
        return "bool";
    }
    if (mxIsSparse(ptr))
    {
        return "sparse";
    }
    if (mxIsInt8(ptr))
    {
        return "int8";
    }
    if (mxIsInt16(ptr))
    {
        return "int16";
    }
    if (mxIsInt32(ptr))
    {
        return "int32";
    }
    if (mxIsInt64(ptr))
    {
        return "int64";
    }
    if (mxIsUint8(ptr))
    {
        return "uint8";
    }
    if (mxIsUint16(ptr))
    {
        return "uint16";
    }
    if (mxIsUint32(ptr))
    {
        return "uint32";
    }
    if (mxIsUint64(ptr))
    {
        return "uint64";
    }
    if (mxIsCell(ptr))
    {
        return "cell";
    }
    if (mxIsStruct(ptr))
    {
        return "struct";
    }
    return "unknown";
}
Ejemplo n.º 6
0
static MAPTYPE *get_maps_3dvol(const mxArray *ptr, int *n)
{
    int num_dims, jj, t, dtype = 0;
    const mwSize *dims;
    MAPTYPE *maps;
    unsigned char *dptr;

    if      (mxIsDouble(ptr)) dtype = SPM_DOUBLE;
    else if (mxIsSingle(ptr)) dtype = SPM_FLOAT;
    else if (mxIsInt32 (ptr)) dtype = SPM_SIGNED_INT;
    else if (mxIsUint32(ptr)) dtype = SPM_UNSIGNED_INT;
    else if (mxIsInt16 (ptr)) dtype = SPM_SIGNED_SHORT;
    else if (mxIsUint16(ptr)) dtype = SPM_UNSIGNED_SHORT;
    else if (mxIsInt8  (ptr)) dtype = SPM_SIGNED_CHAR;
    else if (mxIsUint8 (ptr)) dtype = SPM_UNSIGNED_CHAR;
    else mexErrMsgTxt("Unknown volume datatype.");

    maps = (MAPTYPE *)mxCalloc(1, sizeof(MAPTYPE));

    num_dims = mxGetNumberOfDimensions(ptr);
    if (num_dims > 3)
    {
        mexErrMsgTxt("Too many dimensions.");
    }

    dims     = mxGetDimensions(ptr);
    for(jj=0; jj<num_dims; jj++)
        maps->dim[jj]=dims[jj];
    for(jj=num_dims; jj<3; jj++)
        maps->dim[jj]=1;

    for(jj=0; jj<16; jj++)
        maps->mat[jj] = 0.0;
    for(jj=0; jj<4; jj++)
        maps->mat[jj + jj*4] = 1.0;

    maps->dtype  = dtype;

    maps->data   = (void  **)mxCalloc(maps->dim[2],sizeof(void *));
    maps->scale  = (double *)mxCalloc(maps->dim[2],sizeof(double));
    maps->offset = (double *)mxCalloc(maps->dim[2],sizeof(double));

    t     = maps->dim[0]*maps->dim[1]*get_datasize(maps->dtype)/8;
    dptr   = (unsigned char *)mxGetPr(ptr);

    for(jj=0; jj<maps->dim[2]; jj++)
    {
        maps->scale[jj]  = 1.0;
        maps->offset[jj] = 0.0;
        maps->data[jj]   = &(dptr[jj*t]);
    }

    maps->addr      = 0;
    maps->len       = 0;

    *n = 1;
    return(maps);
}
Ejemplo n.º 7
0
/* Entry Points */
void mexFunction( int nlhs, mxArray *plhs[], 
				 int nrhs, const mxArray *prhs[] ) {

  int MaxComponent;
  int  dim_array[2];  
  float *ComponentHistogram;

  /* Check for proper number of input and output arguments. */    
  if (nrhs != 1 || nlhs != 1) {
    mexErrMsgTxt("Usage: [aiHist] = fnLabelsHist(a3iLabeledVolume)");
	return;
  } 

  if (mxIsUint16(prhs[0])) 
	  MaxComponent = FindMaxComponent((unsigned short *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else if (mxIsUint32(prhs[0]))
	  MaxComponent = FindMaxComponent((int *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else if (mxIsSingle(prhs[0]))
	  MaxComponent = FindMaxComponent((float *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else if (mxIsDouble(prhs[0]))
	  MaxComponent = FindMaxComponent((double *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else {
		mexErrMsgTxt("Use uint16, uint32, float or double only");
		return;
  }

  dim_array[0] = 1;
  dim_array[1] = MaxComponent+1;
  plhs[0] = mxCreateNumericArray(2, dim_array, mxSINGLE_CLASS, mxREAL);
  ComponentHistogram = (float*)mxGetPr(plhs[0]);
  
  if (mxIsUint16(prhs[0])) 
	  CalcHistogram(ComponentHistogram, (unsigned short *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else if (mxIsUint32(prhs[0]))
	  CalcHistogram(ComponentHistogram, (int *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else if (mxIsSingle(prhs[0]))
	  CalcHistogram(ComponentHistogram, (float *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else if (mxIsDouble(prhs[0]))
	  CalcHistogram(ComponentHistogram, (double *)mxGetData(prhs[0]), mxGetNumberOfElements(prhs[0]));
  else {
		mexErrMsgTxt("Use uint16, uint32, float or double only");
		return;
  }

}
Ejemplo n.º 8
0
Archivo: iog2.c Proyecto: seydar/icling
/* ************************************************************** */
void
mexFunction(
  int nlhs, mxArray *plhs[],
  int nrhs, const mxArray *prhs[]
) {
  char *g;            /* M char array data reformatted for C */
  int  oN, iN, gN;    /* lengths of M char array data */
  int f; int* fp;     /* flag bits */
  int idx; short *pr; /* for M mxChar type */
  mwSize dims[2];
  
  /* check inputs */
  mxAssert(nrhs == 2 || nrhs == 3, "bad call: use gem(i,g) or gem(i,g,f)");    
  mxAssert(nlhs<=1, "bad call: use o = gem(i,g)");

  /* grab user input text */
  mxAssert(mxIsChar(prhs[0]),  "bad call 1rst arg: requires char");    
  iN = mxGetM(prhs[0])*mxGetN(prhs[0]);
  mxAssert(iN<DATALIM, "bad call 1rst arg: input is too long");
  pr = (short*)mxGetData(prhs[0]);
  for (idx=0; idx<iN; idx++) input[idx] = (unsigned char)*(pr+idx)&0xFF;
  input[iN] = 0;                            /* null terminate */
  i = input;                                /* the input */
  
  /* grab user grammar */
  mxAssert(mxIsChar(prhs[1]),  "bad call 2nd arg: requires char");   
  gN = mxGetM(prhs[1])*mxGetN(prhs[1]);
  mxAssert(gN<DATALIM, "bad call 2nd arg: input is too long");
  pr = (short*)mxGetData(prhs[1]);
  for (idx=0; idx<gN; idx++) code[idx] = (unsigned char)*(pr+idx)&0xFF;
  code[gN] = 0;                             /* null terminate */
  g = code;                                 /* the code */
  
  /* grab flags */
  if (nrhs == 3) {
    mxAssert(mxIsUint32(prhs[2]), "bad call 3rd arg: requires int32");   
    fp = (int*)mxGetData(prhs[2]);         /* flag bits */
    f = *fp;
  } else {
    f = 0;                                  /* no flags */
  }
  
  pregem(i, iN, g, gN, f);                  /* set up globals */
  gem();                                    /* translate */
  
  /* push output */
  oN = o-output+1;                          /* number of output chars */
  o = output;
  dims[0] = 1; dims[1] = oN;
  plhs[0] = mxCreateCharArray(2, (const mwSize*)&dims); 
  pr = (short*)mxGetData(plhs[0]);          /* 16 bits per char */
  for (idx=0; idx<oN; idx++) *(pr+idx) = (*o++)&0xFF;
}
Ejemplo n.º 9
0
int getUint32Scalar(const mxArray *arg, uint32 *x)
{
  if (!arg) return -1;
  int m = min(mxGetM(arg),mxGetN(arg));
  int n = max(mxGetM(arg),mxGetN(arg));
  if (!mxIsUint32(arg) || m != 1 || n!= 1) {
    *x = 0;
    return -1;
  }
  *x = (*((uint32 *)mxGetData(arg))); 
  return 0;
}
Ejemplo n.º 10
0
// Mapping of scalar buffer offset value (in units of bytes) to an
// equivalent memory void*. Handles doubles, uint32 and uint64:
void* moglScalarToPtrOffset(const mxArray *m) {
	if (mxIsDouble(m)) return((void*) (size_t) mxGetScalar(m));
	if (mxIsUint32(m)) return((void*) (size_t) (((unsigned int*) mxGetData(m))[0]));

    #ifndef MATLABR11
    if (mxIsUint64(m)) return((void*) (size_t) (((psych_uint64*) mxGetData(m))[0]));
	#endif
    
	// Invalid input type - Error abort:
    glBeginLevel = 0;
    printf("MOGL-Command: %s\n", cmd);
	mexErrMsgTxt("Provided pointer or buffer offset argument is of invalid type - Not double, uint32 or uint64!");
	return(NULL);
}
Ejemplo n.º 11
0
void mxSetImagData(mxArray *array_ptr, void *data_ptr)
{
    if (mxIsChar(array_ptr))
    {
        ((String *)array_ptr)->setImg((wchar_t **)data_ptr);
    }
    else if (mxIsDouble(array_ptr))
    {
        ((Double *)array_ptr)->setImg((double *)data_ptr);
    }
    else if (mxIsInt8(array_ptr))
    {
        ((Int8 *)array_ptr)->setImg((char *)data_ptr);
    }
    else if (mxIsInt16(array_ptr))
    {
        ((Int16 *)array_ptr)->setImg((short *)data_ptr);
    }
    else if (mxIsInt32(array_ptr))
    {
        ((Int32 *)array_ptr)->setImg((int *)data_ptr);
    }
    else if (mxIsInt64(array_ptr))
    {
        ((Int64 *)array_ptr)->setImg((long long *)data_ptr);
    }
    else if (mxIsLogical(array_ptr))
    {
        ((Bool *)array_ptr)->setImg((int *)data_ptr);
    }
    // else if (mxIsSingle(array_ptr)) {
    //   ((Float *) array_ptr)->setImg((float *) data_ptr);
    // }
    else if (mxIsUint8(array_ptr))
    {
        ((UInt8 *)array_ptr)->setImg((unsigned char *)data_ptr);
    }
    else if (mxIsUint16(array_ptr))
    {
        ((UInt16 *)array_ptr)->setImg((unsigned short *)data_ptr);
    }
    else if (mxIsUint32(array_ptr))
    {
        ((UInt32 *)array_ptr)->setImg((unsigned int *)data_ptr);
    }
    else if (mxIsUint64(array_ptr))
    {
        ((UInt64 *)array_ptr)->setImg((unsigned long long *) data_ptr);
    }
}
Ejemplo n.º 12
0
void mxSetImagData(mxArray *array_ptr, void *data_ptr)
{
    if (mxIsChar(array_ptr))
    {
        ((types::String *)array_ptr)->setImg((wchar_t **)data_ptr);
    }
    else if (mxIsDouble(array_ptr))
    {
        ((types::Double *)array_ptr)->setImg((double *)data_ptr);
    }
    else if (mxIsInt8(array_ptr))
    {
        ((types::Int8 *)array_ptr)->setImg((char *)data_ptr);
    }
    else if (mxIsInt16(array_ptr))
    {
        ((types::Int16 *)array_ptr)->setImg((short *)data_ptr);
    }
    else if (mxIsInt32(array_ptr))
    {
        ((types::Int32 *)array_ptr)->setImg((int *)data_ptr);
    }
    else if (mxIsInt64(array_ptr))
    {
        ((types::Int64 *)array_ptr)->setImg((long long *)data_ptr);
    }
    else if (mxIsLogical(array_ptr))
    {
        ((types::Bool *)array_ptr)->setImg((int *)data_ptr);
    }
    else if (mxIsUint8(array_ptr))
    {
        ((types::UInt8 *)array_ptr)->setImg((unsigned char *)data_ptr);
    }
    else if (mxIsUint16(array_ptr))
    {
        ((types::UInt16 *)array_ptr)->setImg((unsigned short *)data_ptr);
    }
    else if (mxIsUint32(array_ptr))
    {
        ((types::UInt32 *)array_ptr)->setImg((unsigned int *)data_ptr);
    }
    else if (mxIsUint64(array_ptr))
    {
        ((types::UInt64 *)array_ptr)->setImg((unsigned long long *) data_ptr);
    }
}
Ejemplo n.º 13
0
static void set_object_data(const mxArray *data)
{
	OBJECT *obj;
	mxArray *pId = mxGetField(data,0,"id");
	char id[256];
	if (pId==NULL)
		output_error("set_object_data(const mxArray *data={...}) did not find a required object id field");
	else if (mxGetString(pId,id,sizeof(id)))
		output_error("set_object_data(const mxArray *data={...}) couldn't read the object id field");
	else if ((obj=object_find_name(id))==NULL)
		output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't find object id", id);
	else
	{
		int i;
		for (i=0; i<mxGetNumberOfFields(data); i++)
		{	
			const char *name;
			const mxArray *pField = mxGetFieldByNumber(data,0,i);
			char value[4096];
			if ((name=mxGetFieldNameByNumber(data,i))==NULL)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the name of field %d", id, i);
			else if (strcmp(name,"id")==0 || strcmp(name,"class")==0)
			{	/* these may not be changed */ }
			else if (pField==NULL)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the object field '%s' for object '%s'", id, name);
			else if (mxIsChar(pField) && mxGetString(pField,value,sizeof(value)))
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the string value '%s' from field '%s'", id, value, name);
			else if (mxIsDouble(pField) && sprintf(value,"%lg",*(double*)mxGetPr(pField))<1)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the double value '%lg' from field '%s'", id, *(double*)mxGetPr(pField), name);
			else if (mxIsComplex(pField) && sprintf(value,"%lg%+lgi",*(double*)mxGetPr(pField),*(double*)mxGetPi(pField))<1)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the complex value '%lg%+lgi' from field '%s'", id, *(double*)mxGetPr(pField), *(double*)mxGetPi(pField), name);
			else if (mxIsUint32(pField) && sprintf(value,"%lu",*(unsigned int*)mxGetPr(pField))<1)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the uint32 value '%lu' from field '%s'", id, *(unsigned int*)mxGetPr(pField), name);
			else if (strcmp(value,ERROR)==0)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't use error value '%s'", id, value);
			else if (strcmp(value,NONE)==0 && strcpy(value,"")==NULL)
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't clear empty value '%s'", id, value);
			else if (!object_set_value_by_name(obj,name,value))
				output_error("set_object_data(const mxArray *data={id='%s',...}) couldn't read the value '%s' into property '%s'", id, value, name);
		}
	}
}
Ejemplo n.º 14
0
int getUint32Vector(const mxArray *arg, uint32 **x, int *n)
{
  if (!arg) return -1;
  int m = min(mxGetM(arg),mxGetN(arg));
  *n = max(mxGetM(arg),mxGetN(arg));
  if (!mxIsUint32(arg) || m != 1 ) {
    if (!mxIsNumeric(arg) ||  mxIsComplex(arg) ||  
        mxIsSparse(arg)  || !mxIsDouble(arg)  || m > 1 || m < 0) {
      *x = NULL;
      return -1;
    } else { // this is a double vector so we convert it to a uint32
      double *d = mxGetPr(arg);
      uint32 *u = (*x)  = (uint32 *)mxCalloc(*n,sizeof(uint32));
      for(int i=0;i<*n;i++) {
        u[i] = (uint32)(d[i]);
      }
      return 0;
    }
  }
  *x = (uint32 *)mxGetData(arg); 
  return 0;
}
Ejemplo n.º 15
0
void mexFunction(
          int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray* prhs[] )
{
    uint32_T *I, *J;
    double *A, *B, *X;
    mwSize m, n, r, k1, k2, numit;
    mwIndex k, it;
    
    /* Check for proper number of arguments */
    if (nrhs != 4) { 
        mexErrMsgTxt("Four input arguments are required."); 
    } else if (nlhs != 1) {
        mexErrMsgTxt("A single output argument is required."); 
    } 
    
    /* Check argument classes */
    if(!mxIsUint32(pI) || !mxIsUint32(pJ)) {
        mexErrMsgTxt("I and J must be of class UINT32."); 
    }
    if(!mxIsDouble(pA) || !mxIsDouble(pB)) {
        mexErrMsgTxt("A and B must be of class DOUBLE."); 
    }
    if(mxIsComplex(pA) || mxIsComplex(pB)) {
        mexErrMsgTxt("A and B must be REAL."); 
    }
    
    /* Check the dimensions of input arguments */ 
    m = mxGetM(pA);
    r = mxGetN(pA);
    n = mxGetN(pB);
    k1 = mxGetM(pI);
    k2 = mxGetN(pI);
    
    if(mxGetM(pB) != r)
        mexErrMsgTxt("Matrix dimensions mismatch for A and B.");
    
    if(mxGetM(pJ) != k1 || mxGetN(pJ) != k2)
        mexErrMsgTxt("Matrix dimensions mismatch for I and J.");
    
    
    /* Get pointers to the data in A, B, I, J */
    A = mxGetPr(pA);
    B = mxGetPr(pB);
    I = (uint32_T*) mxGetData(pI);
    J = (uint32_T*) mxGetData(pJ);
    
    /* Create a matrix for the ouput argument */ 
    pX = mxCreateDoubleMatrix(k1, k2, mxREAL);
    if(pX == NULL)
        mexErrMsgTxt("SPMASKMULT: Could not allocate X. Out of memory?");
    X = mxGetPr(pX);
    
    
    /* Compute */
    numit = k1*k2;
    for(it = 0; it < numit; ++it)
    {
        /* Multiply row I(it) of A with col J(it) of B */
        X[it] = A[ I[it]-1 ] * B[ r*(J[it]-1) ];
        for(k = 1; k < r; ++k)
        {
            X[it] += A[ I[it]-1 + m*k ]*B[ k + r*(J[it]-1) ];
        }
    }
    
    return;
}
Ejemplo n.º 16
0
int mxIsNumeric(const mxArray *ptr)
{
    return mxIsDouble(ptr) || mxIsSingle(ptr) ||
           mxIsInt8(ptr) || mxIsUint8(ptr) ||
           mxIsInt16(ptr) || mxIsUint16(ptr) || mxIsInt32(ptr) || mxIsUint32(ptr) || mxIsInt64(ptr) || mxIsUint64(ptr);
}
Ejemplo n.º 17
0
void mexFunction(
    int nargout,
    mxArray *out[],
    int nargin,
    const mxArray *in[]
)
{
    /* declare variables */
    int nr, nc, np, total;
    int i, j, k, ix, iy, jx, jy, ii, jj, iip1, jjp1, iip2, jjp2, step;
    double sigma, di, dj, a, z, maxori, phase1, phase2, slope;
// 	int *ir, *jc;
    mwIndex*ir,*jc;
	unsigned int *pi, *pj;
	double *emag, *ephase, *w;
    
    /* check argument */
    if (nargin<4) {
        mexErrMsgTxt("Four input arguments required");
    }
    if (nargout>1) {
        mexErrMsgTxt("Too many output arguments");
    }

    /* get edgel information */
	nr = mxGetM(in[0]);
	nc = mxGetN(in[0]);
	if ( nr*nc ==0 || nr != mxGetM(in[1]) || nc != mxGetN(in[1]) ) {
	    mexErrMsgTxt("Edge magnitude and phase shall be of the same image size");
	}
    emag = mxGetPr(in[0]);
    ephase = mxGetPr(in[1]);
    np = nr * nc;
    
    /* get new index pair */
    if (!mxIsUint32(in[2]) | !mxIsUint32(in[3])) {
        mexErrMsgTxt("Index pair shall be of type UINT32");
    }
    if (mxGetM(in[3]) * mxGetN(in[3]) != np + 1) {
        mexErrMsgTxt("Wrong index representation");
    }
    pi = (unsigned int*)mxGetData(in[2]); /* pointer to w_i */
    pj = (unsigned int*)mxGetData(in[3]); /* pointer to w_j */   

    /* create output */
    out[0] = mxCreateSparse(np,np,pj[np],mxREAL);
    if (out[0]==NULL) {
	    mexErrMsgTxt("Not enough memory for the output matrix");
	}
	w = mxGetPr(out[0]);
	ir = mxGetIr(out[0]); /* */
	jc = mxGetJc(out[0]);
	
    /* find my sigma */
	if (nargin<5) {
	    sigma = 0;
    	for (k=0; k<np; k++) { 
    	    if (emag[k]>sigma) { sigma = emag[k]; }
    	}
    	sigma = sigma / 6;
    	printf("sigma = %6.5f",sigma);
	} else {
	    sigma = mxGetScalar(in[4]);
	}
	a = 0.5 / (sigma * sigma);
	
    /* computation */ 
    total = 0;
    for (j=0; j<np; j++) {            

        jc[j] = total;
        jx = j / nr; /* col */
        jy = j % nr; /* row */
        
        for (k=pj[j]; k<pj[j+1]; k++) {
        
            i = pi[k];
          
            if (i==j) {
                maxori = 1;
            
            } else {
        
                ix = i / nr; 
                iy = i % nr;

                /* scan */            
                di = (double) (iy - jy);
                dj = (double) (ix - jx);
            
                maxori = 0.;
	            phase1 = ephase[j];

	               
                /* sample in i direction */
                if (abs(di) >= abs(dj)) {  
            	    slope = dj / di;
            	    step = (iy>=jy) ? 1 : -1;
            	
              	    iip1 = jy;
            	    jjp1 = jx;
	
	               
	                for (ii=0;ii<abs(di);ii++){
	                    iip2 = iip1 + step;
	                    jjp2 = (int)(0.5 + slope*(iip2-jy) + jx);
	  	  
	                    phase2 = ephase[iip2+jjp2*nr];
               
	                    if (phase1 != phase2) {
	                        z = (emag[iip1+jjp1*nr] + emag[iip2+jjp2*nr]);
	                        if (z > maxori){
	                            maxori = z;
	                        }
	                    } 
	             
	                    iip1 = iip2;
	                    jjp1 = jjp2;
	                    phase1 = phase2;
	                }
	            
	            /* sample in j direction */    
                } else { 
	                slope = di / dj;
	                step =  (ix>=jx) ? 1: -1;

    	            jjp1 = jx;
	                iip1 = jy;	           
	    
	 
	                for (jj=0;jj<abs(dj);jj++){
	                    jjp2 = jjp1 + step;
	                    iip2 = (int)(0.5+ slope*(jjp2-jx) + jy);
	  	  
	                    phase2 = ephase[iip2+jjp2*nr];
	     
	                    if (phase1 != phase2){
	                        z = (emag[iip1+jjp1*nr] + emag[iip2+jjp2*nr]);
	                        if (z > maxori){ 
	                            maxori = z; 
	                        }
	                        
	                    }
	  
	                    iip1 = iip2;
	                    jjp1 = jjp2;
	                    phase1 = phase2;
	                }
                }            
            
                maxori = 0.5 * maxori; 
                //maxori = exp(-maxori * maxori * a); //segmentation
                maxori = 1-exp(-maxori * maxori * a); //symmetry
            }       
		    ir[total] = i;

		    if (maxori>0.2) w[total] = maxori; else w[total]=0.2; //symmetry
            //w[total] = maxori; //segmentation

		    total = total + 1;
			
		} /* i */
    } /* j */
        
    jc[np] = total;
}  
Ejemplo n.º 18
0
int mxIsClass(const mxArray *ptr, const char *name)
{
    if (strcmp(name, "cell") == 0)
    {
        return mxIsCell(ptr);
    }
    if (strcmp(name, "char") == 0)
    {
        return mxIsChar(ptr);
    }
    if (strcmp(name, "double") == 0)
    {
        return mxIsDouble(ptr);
    }
    if (strcmp(name, "int8") == 0)
    {
        return mxIsInt8(ptr);
    }
    if (strcmp(name, "int16") == 0)
    {
        return mxIsInt16(ptr);
    }
    if (strcmp(name, "int32") == 0)
    {
        return mxIsInt32(ptr);
    }
    if (strcmp(name, "int64") == 0)
    {
        return mxIsInt64(ptr);
    }
    if (strcmp(name, "logical") == 0)
    {
        return mxIsLogical(ptr);
    }
    if (strcmp(name, "single") == 0)
    {
        return mxIsSingle(ptr);
    }
    if (strcmp(name, "struct") == 0)
    {
        return mxIsStruct(ptr);
    }
    if (strcmp(name, "uint8") == 0)
    {
        return mxIsUint8(ptr);
    }
    if (strcmp(name, "uint16") == 0)
    {
        return mxIsUint16(ptr);
    }
    if (strcmp(name, "uint32") == 0)
    {
        return mxIsUint32(ptr);
    }
    if (strcmp(name, "uint64") == 0)
    {
        return mxIsUint64(ptr);
    }
    // TODO: how to handle <class_name> and <class_id>?
    return 0;
}
Ejemplo n.º 19
0
int mxSetDimensions(mxArray *array_ptr, const int *dims, int ndim)
{
    if (mxIsCell(array_ptr))
    {
        ((types::Cell *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsChar(array_ptr))
    {
        ((types::String *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsDouble(array_ptr))
    {
        ((types::Double *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsSparse(array_ptr))
    {
        //TODO
    }
    else if (mxIsInt8(array_ptr))
    {
        ((types::Int8 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsInt16(array_ptr))
    {
        ((types::Int16 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsInt32(array_ptr))
    {
        ((types::Int32 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsInt64(array_ptr))
    {
        ((types::Int64 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsLogical(array_ptr))
    {
        ((types::Bool *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsStruct(array_ptr))
    {
        ((types::Struct *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsUint8(array_ptr))
    {
        ((types::UInt8 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsUint16(array_ptr))
    {
        ((types::UInt16 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsUint32(array_ptr))
    {
        ((types::UInt32 *)array_ptr)->resize((int *)dims, ndim);
    }
    else if (mxIsUint64(array_ptr))
    {
        ((types::UInt64 *)array_ptr)->resize((int *)dims, ndim);
    }

    return 0;
}
Ejemplo n.º 20
0
int isFunctionHandle( const mxArray* const M )
{
	if ( M == NULL )
		return 0;

	if ( mxIsCell(M) )
		return 0;

	if ( mxIsChar(M) )
		return 0;

	if ( mxIsComplex(M) )
		return 0;

	if ( mxIsDouble(M) )
		return 0;

	if ( mxIsEmpty(M) )
		return 0;

	if ( mxIsInt8(M) )
		return 0;

	if ( mxIsInt16(M) )
		return 0;

	if ( mxIsInt32(M) )
		return 0;

	if ( mxIsLogical(M) )
		return 0;

	if ( mxIsLogicalScalar(M) )
		return 0;

	if ( mxIsLogicalScalarTrue(M) )
		return 0;

	if ( mxIsNumeric(M) )
		return 0;

	if ( mxIsSingle(M) )
		return 0;

	if ( mxIsSparse(M) )
		return 0;

	if ( mxIsStruct(M) )
		return 0;

	if ( mxIsUint8(M) )
		return 0;

	if ( mxIsUint16(M) )
		return 0;

	if ( mxIsUint32(M) )
		return 0;

	// assume to be a function handle iff it is nothing else
	return 1;
}
Ejemplo n.º 21
0
Image Matlab2ViLi(const mxArray *In) {

Image Res;
int Type;
int i, j, k;

if (mxIsUint8(In)) {
      Type = IM_BYTE;
} else if (mxIsInt16(In)) {
      Type = IM_SHORT;
} else if (mxIsUint32(In)) {
      Type = IM_LONG;
} else if (mxIsDouble(In)||mxIsSingle(In)) {
		if (mxIsComplex(In)) {
	   	Type = IM_COMPLEX;
		}
		else {
		   Type = IM_FLOAT;
		}
} else {
      mexErrMsgTxt("Array type not supported");
}
      
if (mxGetNumberOfDimensions(In) == 2) {
      Res = NewImage("from MATLAB", Type, mxGetDimensions(In)[1], mxGetDimensions(In)[0], 1, 1, GRID_RECT);
} else if ( (mxGetNumberOfDimensions(In) == 3) && (mxGetDimensions(In)[2] == 3)) {
         Res = NewImage("from MATLAB", Type, mxGetDimensions(In)[1], mxGetDimensions(In)[0], 1,  mxGetDimensions(In)[2], GRID_RECT);
} else if ( (mxGetNumberOfDimensions(In) == 3) && (mxGetDimensions(In)[2] != 3)) {
         Res = NewImage("from MATLAB", Type, mxGetDimensions(In)[1], mxGetDimensions(In)[0], mxGetDimensions(In)[2], 1, GRID_RECT);
} else if (mxGetNumberOfDimensions(In) == 4) {
         Res = NewImage("from MATLAB", Type, mxGetDimensions(In)[1], mxGetDimensions(In)[0], mxGetDimensions(In)[2], mxGetDimensions(In)[3], GRID_RECT);
} else {
     mexErrMsgTxt("Dimensions not supported");
}

switch(Type) {
      case IM_BYTE:
			{
         unsigned char *pIn, *pRes;
         pRes = (unsigned char *) Res->Data;
         pIn = (unsigned char *) mxGetData(In);
			/* Copia transponiendo filas y columnas */
			for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
				for (j=0; j<Res->NCol; j++) {
					for (i=0; i<Res->NLin; i++) {
						pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin] =
							pIn[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
					}
				}
			}
			}
         break;
      case IM_SHORT:
			{
         short *pIn, *pRes;
         pRes = (short *) Res->Data;
         pIn = (short *) mxGetData(In);
			/* Copia transponiendo filas y columnas */
			for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
				for (j=0; j<Res->NCol; j++) {
					for (i=0; i<Res->NLin; i++) {
						pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin] =
							pIn[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
					}
				}
			}
			}
         break;
      case IM_LONG:
			{
         unsigned long *pIn, *pRes;
         pRes = (unsigned long *) Res->Data;
         pIn = (unsigned long *) mxGetData(In);
			/* Copia transponiendo filas y columnas */
			for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
				for (j=0; j<Res->NCol; j++) {
					for (i=0; i<Res->NLin; i++) {
						pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin] =
							pIn[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
					}
				}
			}
			}
         break;
      case IM_FLOAT:
			{
			float *pRes;
         	pRes = (float *) Res->Data;
         	if (mxIsSingle(In)){
	        	float *pIn;
         		pIn = (float *) mxGetData(In);
				/* Copia transponiendo filas y columnas */
				for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
					for (j=0; j<Res->NCol; j++) {
						for (i=0; i<Res->NLin; i++) {
							pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin] =
								(float) pIn[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
						}
					}
				}
			} else {
	        	double *pIn;
         		pIn = (double *) mxGetData(In);
				/* Copia transponiendo filas y columnas */
				for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
					for (j=0; j<Res->NCol; j++) {
						for (i=0; i<Res->NLin; i++) {
							pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin] =
								(float) pIn[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
						}
					}
				}
			}
			}
         break;
		case IM_COMPLEX:
			{
			Complex *pRes;
	        pRes = (Complex *) Res->Data;
           	if (mxIsSingle(In)){
	        	float *pInR, *pInI;
	    	    pInR = mxGetPr(In);
	        	pInI = mxGetPi(In);
	
				/* Copia transponiendo filas y columnas */
				for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
					for (j=0; j<Res->NCol; j++) {
						for (i=0; i<Res->NLin; i++) {
							pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin].Re =
								(float) pInR[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
							pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin].Im =
								(float) pInI[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
						}
					}
				}
			} else {
	        	double *pInR, *pInI;
	    	    pInR = mxGetPr(In);
	        	pInI = mxGetPi(In);
	
				/* Copia transponiendo filas y columnas */
				for (k=0; k<Res->NPlanes * Res->NChannels; k++) {
					for (j=0; j<Res->NCol; j++) {
						for (i=0; i<Res->NLin; i++) {
							pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin].Re =
								(float) pInR[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
							pRes[ j + i * Res->NCol + k * Res->NCol * Res->NLin].Im =
								(float) pInI[ i + j * Res->NLin + k * Res->NCol * Res->NLin];
						}
					}
				}
			}
			}
         break;
	
}
   
return Res;
}
Ejemplo n.º 22
0
/* Matlab Gateway routine */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	int	nXYSize;
	double	adfGeoTransform[6] = {0,1,0,0,0,1}, adfDstGeoTransform[6];
	char	*pszSRS_WKT = NULL;
	char	**papszWarpOptions = NULL;
	GDALDatasetH	hSrcDS, hDstDS;
	GDALDriverH	hDriver;
	GDALRasterBandH hBand;
	GDALColorTableH	hColorTable = NULL;
	OGRSpatialReference oSrcSRS, oDstSRS; 
	GDALResampleAlg	interpMethod = GRA_NearestNeighbour;
	GDALTransformerFunc pfnTransformer = NULL;
	CPLErr		eErr;
	GDAL_GCP	*pasGCPs = NULL;
	static int runed_once = FALSE;	/* It will be set to true if reaches end of main */

	const int *dim_array;
	int	nx, ny, i, j, m, n, c, nBands, registration = 1;
	int	n_dims, typeCLASS, nBytes;
	char	*pszSrcSRS = NULL, *pszSrcWKT = NULL;
	char	*pszDstSRS = NULL, *pszDstWKT = NULL;
	void	*in_data;
	mxArray	*mx_ptr;

	unsigned char *tmpByte, *outByte;
	unsigned short int *tmpUI16, *outUI16;
	short int *tmpI16, *outI16;
	int	*tmpI32, *outI32;
	int	nPixels=0, nLines=0, nForceWidth=0, nForceHeight=0;
	int	nGCPCount = 0, nOrder = 0;
	unsigned int *tmpUI32, *outUI32;
	float	*tmpF32, *outF32;
	double	*tmpF64, *outF64, *ptr_d;
	double	dfMinX=0, dfMaxX=0, dfMinY=0, dfMaxY=0, dfResX=0, dfResY=0;
	double	adfExtent[4];
	double	dfXRes=0.0, dfYRes=0.0;
	double	dfWarpMemoryLimit = 0.0;
	double	*pdfDstNodata = NULL; 
	char	**papszMetadataOptions = NULL;
	char	*tmp, *txt;


	if (nrhs == 2 && mxIsStruct(prhs[1])) {
		mx_ptr = mxGetField(prhs[1], 0, "ULx");
		if (mx_ptr == NULL)
			mexErrMsgTxt("GDALWARP 'ULx' field not provided");
		ptr_d = mxGetPr(mx_ptr);
		adfGeoTransform[0] = *ptr_d;

		mx_ptr = mxGetField(prhs[1], 0, "Xinc");
		if (mx_ptr == NULL)
			mexErrMsgTxt("GDALWARP 'Xinc' field not provided");
		ptr_d = mxGetPr(mx_ptr);
		adfGeoTransform[1] = *ptr_d;

		mx_ptr = mxGetField(prhs[1], 0, "ULy");
		if (mx_ptr == NULL)
			mexErrMsgTxt("GDALWARP 'ULy' field not provided");
		ptr_d = mxGetPr(mx_ptr);
		adfGeoTransform[3] = *ptr_d;

		mx_ptr = mxGetField(prhs[1], 0, "Yinc");
		if (mx_ptr == NULL)
			mexErrMsgTxt("GDALWARP 'Yinc' field not provided");
		ptr_d = mxGetPr(mx_ptr);
		adfGeoTransform[5] = -*ptr_d;

		/* -------- See for resolution requests ------------ */
		mx_ptr = mxGetField(prhs[1], 0, "t_size");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			if (mxGetN(mx_ptr) == 2) {
				nForceWidth  = (int)ptr_d[0];
				nForceHeight = (int)ptr_d[1];
			}
			else if (mxGetN(mx_ptr) == 1) {	/* pick max(nrow,ncol) */
				if (mxGetM(prhs[0]) > getNK(prhs[0],1))
					nForceHeight = mxGetM(prhs[0]);
				else
					nForceWidth  = getNK(prhs[0], 1);
			}
			else {
				nForceHeight = mxGetM(prhs[0]);
				nForceWidth  = getNK(prhs[0], 1);
			}
		}

		mx_ptr = mxGetField(prhs[1], 0, "t_res");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			if (mxGetN(mx_ptr) == 2) {
				dfXRes = ptr_d[0];
				dfYRes = ptr_d[1];
			}
			else if (mxGetN(mx_ptr) == 1) {
				dfXRes = dfYRes = ptr_d[0];
			}
		}
		/* -------------------------------------------------- */

		/* -------- Change Warping cache size?  ------------ */
		mx_ptr = mxGetField(prhs[1], 0, "wm");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			dfWarpMemoryLimit = *ptr_d * 1024 * 1024;
		}
		/* -------------------------------------------------- */

		/* -------- Have a nodata value order? -------------- */
		mx_ptr = mxGetField(prhs[1], 0, "nodata");
		if (mx_ptr != NULL) {
			pdfDstNodata = mxGetPr(mx_ptr);
		}
		/* -------------------------------------------------- */

		/* -------- See for projection stuff ---------------- */
		mx_ptr = mxGetField(prhs[1], 0, "SrcProjSRS");
		if (mx_ptr != NULL)
			pszSrcSRS = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "SrcProjWKT");
		if (mx_ptr != NULL)
			pszSrcWKT = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "DstProjSRS");
		if (mx_ptr != NULL)
			pszDstSRS = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "DstProjWKT");
		if (mx_ptr != NULL)
			pszDstWKT = (char *)mxArrayToString(mx_ptr);
		/* -------------------------------------------------- */

		/* -------- Do we have GCPs? ----------------------- */
		mx_ptr = mxGetField(prhs[1], 0, "gcp");
		if (mx_ptr != NULL) {
			nGCPCount = mxGetM(mx_ptr);
			if (mxGetN(mx_ptr) != 4)
				mexErrMsgTxt("GDALWARP: GCPs must be a Mx4 array");
			ptr_d = mxGetPr(mx_ptr);
			pasGCPs = (GDAL_GCP *) mxCalloc( nGCPCount, sizeof(GDAL_GCP) );
			GDALInitGCPs( 1, pasGCPs + nGCPCount - 1 );
			for (i = 0; i < nGCPCount; i++) {
				pasGCPs[i].dfGCPPixel = ptr_d[i];
				pasGCPs[i].dfGCPLine = ptr_d[i+nGCPCount];
				pasGCPs[i].dfGCPX = ptr_d[i+2*nGCPCount];
				pasGCPs[i].dfGCPY = ptr_d[i+3*nGCPCount];
				pasGCPs[i].dfGCPZ = 0;
			}
		}
			/* ---- Have we an order request? --- */
		mx_ptr = mxGetField(prhs[1], 0, "order");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			nOrder = (int)*ptr_d;
			if (nOrder != -1 || nOrder != 0 || nOrder != 1 || nOrder != 2 || nOrder != 3)
				nOrder = 0;
		}
		/* -------------------------------------------------- */

		mx_ptr = mxGetField(prhs[1], 0, "ResampleAlg");
		if (mx_ptr != NULL) {
			txt = (char *)mxArrayToString(mx_ptr);
			if (!strcmp(txt,"nearest"))
				interpMethod = GRA_NearestNeighbour;
			else if (!strcmp(txt,"bilinear"))
				interpMethod = GRA_Bilinear;
			else if (!strcmp(txt,"cubic") || !strcmp(txt,"bicubic"))
				interpMethod = GRA_Cubic;
			else if (!strcmp(txt,"spline"))
				interpMethod = GRA_CubicSpline;
		}

		/* If grid limits were in grid registration, convert them to pixel reg */
		mx_ptr = mxGetField(prhs[1], 0, "Reg");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			registration = (int)ptr_d[0];
		}

		if (registration == 0) {
			adfGeoTransform[0] -= adfGeoTransform[1]/2.;
			adfGeoTransform[3] -= adfGeoTransform[5]/2.;
		}
	}
	else {
		mexPrintf("Usage: B = gdalwarp_mex(IMG,HDR_STRUCT)\n\n");
		mexPrintf("\tIMG -> is a Mx2 or Mx3 array with an grid/image data to reproject\n");
		mexPrintf("\tHDR_STRUCT -> is a structure with the following fields:\n");
		mexPrintf("\t\t'ULx' X coordinate of the uper left corner\n");
		mexPrintf("\t\t'ULy' Y coordinate of the uper left corner\n");
		mexPrintf("\t\t'Xinc' distance between columns in target grid/image coordinates\n");
		mexPrintf("\t\t'Yinc' distance between rows in target grid/image coordinates\n");
		mexPrintf("\t\t'SrcProjSRS', 'SrcProjWKT' -> Source projection string\n");
		mexPrintf("\t\t'DstProjSRS', 'DstProjWKT' -> Target projection string\n");
		mexPrintf("\t\t\tSRS stands for a string of the type used by proj4\n");
		mexPrintf("\t\t\tWKT stands for a string on the 'Well Known Text' format\n\n");
		mexPrintf("\t\t\tIf one of the Src or Dst fields is absent a GEOGRAPHIC WGS84 is assumed\n");
		mexPrintf("\nOPTIONS\n");
		mexPrintf("\t\t'gcp' a [Mx4] array with Ground Control Points\n");
		mexPrintf("\t\t't_size' a [width height] vector to set output file size in pixels\n");
		mexPrintf("\t\t't_res' a [xres yres] vector to set output file resolution (in target georeferenced units)\n");
		mexPrintf("\t\t'wm' amount of memory (in megabytes) that the warp API is allowed to use for caching\n");
		mexPrintf("\t\t'nodata' Set nodata values for output bands.\n");
		mexPrintf("\t\t'ResampleAlg' To set up the algorithm used during warp operation. Options are: \n");
		mexPrintf("\t\t\t'nearest' Use nearest neighbour resampling (default, fastest algorithm, worst interpolation quality).\n");
		mexPrintf("\t\t\t'bilinear' Use bilinear resampling.\n");
		mexPrintf("\t\t\t'cubic' Use cubic resampling.\n");
		mexPrintf("\t\t\t'spline' Use cubic spline resampling.\n\n");

		if (!runed_once)		/* Do next call only at first time this MEX is loaded */
			GDALAllRegister();

        	mexPrintf( "The following format drivers are configured and support Create() method:\n" );
        	for( i = 0; i < GDALGetDriverCount(); i++ ) {
			hDriver = GDALGetDriver(i);
			if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL)
				mexPrintf("%s: %s\n", GDALGetDriverShortName(hDriver), 
							GDALGetDriverLongName(hDriver));
		}
		return;
	}

	n_dims = mxGetNumberOfDimensions(prhs[0]);
	dim_array=mxGetDimensions(prhs[0]);
	ny = dim_array[0];
	nx = dim_array[1];
	nBands = dim_array[2];

	if (n_dims == 2)	/* Otherwise it would stay undefined */
		nBands = 1;

	/* Find out in which data type was given the input array */
	if (mxIsUint8(prhs[0])) {
		typeCLASS = GDT_Byte;		nBytes = 1;
		outByte = (unsigned char *)mxMalloc (nx*ny * sizeof(unsigned char));
	}
	else if (mxIsUint16(prhs[0])) {
		typeCLASS = GDT_UInt16;		nBytes = 2;
		outUI16 = (unsigned short int *)mxMalloc (nx*ny * sizeof(short int));
	}
	else if (mxIsInt16(prhs[0])) {
		typeCLASS = GDT_Int16;		nBytes = 2;
		outI16 = (short int *)mxMalloc (nx*ny * sizeof(short int));
	}
	else if (mxIsInt32(prhs[0])) {
		typeCLASS = GDT_Int32;		nBytes = 4;
		outI32 = (int *)mxMalloc (nx*ny * sizeof(int));
	}
	else if (mxIsUint32(prhs[0])) {
		typeCLASS = GDT_UInt32;		nBytes = 4;
		outUI32 = (unsigned int *)mxMalloc (nx*ny * sizeof(int));
	}
	else if (mxIsSingle(prhs[0])) {
		typeCLASS = GDT_Float32;	nBytes = 4;
		outF32 = (float *)mxMalloc (nx*ny * sizeof(float));
	}
	else if (mxIsDouble(prhs[0])) {
		typeCLASS = GDT_Float64;	nBytes = 8;
		outF64 = (double *)mxMalloc (nx*ny * sizeof(double));
	}
	else
		mexErrMsgTxt("GDALWARP Unknown input data class!");


	in_data = (void *)mxGetData(prhs[0]);

	if (!runed_once)		/* Do next call only at first time this MEX is loaded */
		GDALAllRegister();

	hDriver = GDALGetDriverByName( "MEM" ); 

	hSrcDS = GDALCreate( hDriver, "mem", nx, ny, nBands, (GDALDataType)typeCLASS, NULL );
	if (hSrcDS == NULL) {
		mexPrintf ("GDALOpen failed - %d\n%s\n", CPLGetLastErrorNo(), CPLGetLastErrorMsg());
		return;
	}
	GDALSetGeoTransform( hSrcDS, adfGeoTransform ); 

	/* ---------- Set the Source projection ---------------------------- */
	/* If it was not provided assume it is Geog WGS84 */
	if (pszSrcSRS == NULL && pszSrcWKT == NULL)
		oSrcSRS.SetWellKnownGeogCS( "WGS84" ); 
	else if (pszSrcWKT != NULL)
		oSrcSRS.importFromWkt( &pszSrcWKT );

	else {
		if( oSrcSRS.SetFromUserInput( pszSrcSRS ) != OGRERR_NONE )
			mexErrMsgTxt("GDAL_WARP_MEX: Translating source SRS failed.");
	}
	if (pszSrcWKT == NULL)
		oSrcSRS.exportToWkt( &pszSrcWKT );

	GDALSetProjection( hSrcDS, pszSrcWKT );	
	//pszSrcWKT = (char *)GDALGetProjectionRef( hSrcDS );
	CPLAssert( pszSrcWKT != NULL && strlen(pszSrcWKT) > 0 );
	/* ------------------------------------------------------------------ */


	/* -------------- Copy input data into the hSrcDS dataset ----------- */
	for (i = 1; i <= nBands; i++) {
		hBand = GDALGetRasterBand( hSrcDS, i ); 
		nXYSize = (i-1)*nx*ny;
		switch( typeCLASS ) {
			case GDT_Byte:
			 	tmpByte = (unsigned char *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outByte[c++] = tmpByte[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outByte, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
			case GDT_UInt16:
			 	tmpUI16 = (unsigned short int *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outUI16[c++] = tmpUI16[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outUI16, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
			case GDT_Int16:
			 	tmpI16 = (short int *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outI16[c++] = tmpI16[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outI16, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
			case GDT_UInt32:
			 	tmpUI32 = (unsigned int *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outUI32[c++] = tmpUI32[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outUI32, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
			case GDT_Int32:
			 	tmpI32 = (int *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outI32[c++] = tmpI32[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outI32, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
			case GDT_Float32:
			 	tmpF32 = (float *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outF32[c++] = tmpF32[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outF32, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
			case GDT_Float64:
			 	tmpF64 = (double *)in_data;	
				for (m = ny-1, c = 0; m >= 0; m--) for (n = 0; n < nx; n++)
					outF64[c++] = tmpF64[m + n*ny + nXYSize];
				GDALRasterIO( hBand, GF_Write, 0, 0, nx, ny,outF64, nx, ny, (GDALDataType)typeCLASS, 0, 0 );
				break;
		}
	}

	/* ---------- Set up the Target coordinate system ------------------- */
	/* If it was not provided assume it is Geog WGS84 */
	CPLErrorReset();
	if (pszDstSRS == NULL && pszDstWKT == NULL)
		oDstSRS.SetWellKnownGeogCS( "WGS84" ); 
	else if (pszDstWKT != NULL)
		oDstSRS.importFromWkt( &pszDstWKT );
	else {
		if( oDstSRS.SetFromUserInput( pszDstSRS ) != OGRERR_NONE )
			mexErrMsgTxt("GDAL_WARP_MEX: Translating target SRS failed.");
	}
	if (pszDstWKT == NULL)
		oDstSRS.exportToWkt( &pszDstWKT );
	/* ------------------------------------------------------------------ */

	if ( nGCPCount != 0 ) {
		if (GDALSetGCPs(hSrcDS, nGCPCount, pasGCPs, "") != CE_None)
			mexPrintf("GDALWARP WARNING: writing GCPs failed.\n");
	}

	/* Create a transformer that maps from source pixel/line coordinates
	   to destination georeferenced coordinates (not destination pixel line) 
	   We do that by omitting the destination dataset handle (setting it to NULL). */

	void *hTransformArg;

	hTransformArg = GDALCreateGenImgProjTransformer(hSrcDS, pszSrcWKT, NULL, pszDstWKT, 
											nGCPCount == 0 ? FALSE : TRUE, 0, nOrder);
	if( hTransformArg == NULL )
		mexErrMsgTxt("GDALTRANSFORM: Generating transformer failed.");

	GDALTransformerInfo *psInfo = (GDALTransformerInfo*)hTransformArg;

	/* -------------------------------------------------------------------------- */
	/*      Get approximate output georeferenced bounds and resolution for file
	/* -------------------------------------------------------------------------- */
	if (GDALSuggestedWarpOutput2(hSrcDS, GDALGenImgProjTransform, hTransformArg, 
	                             adfDstGeoTransform, &nPixels, &nLines, adfExtent,
	                             0) != CE_None ) {
	    GDALClose(hSrcDS);
		mexErrMsgTxt("GDALWARP: GDALSuggestedWarpOutput2 failed.");
	}

	if (CPLGetConfigOption( "CHECK_WITH_INVERT_PROJ", NULL ) == NULL) {
		double MinX = adfExtent[0];
		double MaxX = adfExtent[2];
		double MaxY = adfExtent[3];
		double MinY = adfExtent[1];
		int bSuccess = TRUE;
            
		/* Check that the the edges of the target image are in the validity area */
		/* of the target projection */
#define N_STEPS 20
		for (i = 0; i <= N_STEPS && bSuccess; i++) {
			for (j = 0; j <= N_STEPS && bSuccess; j++) {
				double dfRatioI = i * 1.0 / N_STEPS;
				double dfRatioJ = j * 1.0 / N_STEPS;
				double expected_x = (1 - dfRatioI) * MinX + dfRatioI * MaxX;
				double expected_y = (1 - dfRatioJ) * MinY + dfRatioJ * MaxY;
				double x = expected_x;
				double y = expected_y;
				double z = 0;
				/* Target SRS coordinates to source image pixel coordinates */
				if (!psInfo->pfnTransform(hTransformArg, TRUE, 1, &x, &y, &z, &bSuccess) || !bSuccess)
					bSuccess = FALSE;
				/* Source image pixel coordinates to target SRS coordinates */
				if (!psInfo->pfnTransform(hTransformArg, FALSE, 1, &x, &y, &z, &bSuccess) || !bSuccess)
					bSuccess = FALSE;
				if (fabs(x - expected_x) > (MaxX - MinX) / nPixels ||
					fabs(y - expected_y) > (MaxY - MinY) / nLines)
					bSuccess = FALSE;
			}
		}
            
		/* If not, retry with CHECK_WITH_INVERT_PROJ=TRUE that forces ogrct.cpp */
		/* to check the consistency of each requested projection result with the */
		/* invert projection */
		if (!bSuccess) {
			CPLSetConfigOption( "CHECK_WITH_INVERT_PROJ", "TRUE" );
			CPLDebug("WARP", "Recompute out extent with CHECK_WITH_INVERT_PROJ=TRUE");

			if (GDALSuggestedWarpOutput2(hSrcDS, GDALGenImgProjTransform, hTransformArg, 
			                             adfDstGeoTransform, &nPixels, &nLines, adfExtent,
			                              0) != CE_None ) {
			    GDALClose(hSrcDS);
				mexErrMsgTxt("GDALWARO: GDALSuggestedWarpOutput2 failed.");
			}
		}
	}

	/* -------------------------------------------------------------------- */
	/*      Expand the working bounds to include this region, ensure the    */
	/*      working resolution is no more than this resolution.             */
	/* -------------------------------------------------------------------- */
	if( dfMaxX == 0.0 && dfMinX == 0.0 ) {
		dfMinX = adfExtent[0];
		dfMaxX = adfExtent[2];
		dfMaxY = adfExtent[3];
		dfMinY = adfExtent[1];
		dfResX = adfDstGeoTransform[1];
		dfResY = ABS(adfDstGeoTransform[5]);
	}
	else {
		dfMinX = MIN(dfMinX,adfExtent[0]);
		dfMaxX = MAX(dfMaxX,adfExtent[2]);
		dfMaxY = MAX(dfMaxY,adfExtent[3]);
		dfMinY = MIN(dfMinY,adfExtent[1]);
		dfResX = MIN(dfResX,adfDstGeoTransform[1]);
		dfResY = MIN(dfResY,ABS(adfDstGeoTransform[5]));
	}

	GDALDestroyGenImgProjTransformer( hTransformArg );

	/* -------------------------------------------------------------------- */
	/*      Turn the suggested region into a geotransform and suggested     */
	/*      number of pixels and lines.                                     */
	/* -------------------------------------------------------------------- */

	adfDstGeoTransform[0] = dfMinX;
	adfDstGeoTransform[1] = dfResX;
	adfDstGeoTransform[2] = 0.0;
	adfDstGeoTransform[3] = dfMaxY;
	adfDstGeoTransform[4] = 0.0;
	adfDstGeoTransform[5] = -1 * dfResY;

	nPixels = (int) ((dfMaxX - dfMinX) / dfResX + 0.5);
	nLines  = (int) ((dfMaxY - dfMinY) / dfResY + 0.5);

	/* -------------------------------------------------------------------- */
	/*      Did the user override some parameters?                          */
	/* -------------------------------------------------------------------- */
	if( dfXRes != 0.0 && dfYRes != 0.0 ) {
		dfMinX = adfDstGeoTransform[0];
		dfMaxX = adfDstGeoTransform[0] + adfDstGeoTransform[1] * nPixels;
		dfMaxY = adfDstGeoTransform[3];
		dfMinY = adfDstGeoTransform[3] + adfDstGeoTransform[5] * nLines;

		nPixels = (int) ((dfMaxX - dfMinX + (dfXRes/2.0)) / dfXRes);
		nLines = (int) ((dfMaxY - dfMinY + (dfYRes/2.0)) / dfYRes);
		adfDstGeoTransform[0] = dfMinX;
		adfDstGeoTransform[3] = dfMaxY;
		adfDstGeoTransform[1] = dfXRes;
		adfDstGeoTransform[5] = -dfYRes;
	}
	else if( nForceWidth != 0 && nForceHeight != 0 ) {
		dfXRes = (dfMaxX - dfMinX) / nForceWidth;
		dfYRes = (dfMaxY - dfMinY) / nForceHeight;

		adfDstGeoTransform[0] = dfMinX;
		adfDstGeoTransform[3] = dfMaxY;
		adfDstGeoTransform[1] = dfXRes;
		adfDstGeoTransform[5] = -dfYRes;

		nPixels = nForceWidth;
		nLines = nForceHeight;
	}
	else if( nForceWidth != 0) {
		dfXRes = (dfMaxX - dfMinX) / nForceWidth;
		dfYRes = dfXRes;

		adfDstGeoTransform[0] = dfMinX;
		adfDstGeoTransform[3] = dfMaxY;
		adfDstGeoTransform[1] = dfXRes;
		adfDstGeoTransform[5] = -dfYRes;

		nPixels = nForceWidth;
		nLines = (int) ((dfMaxY - dfMinY + (dfYRes/2.0)) / dfYRes);
	}
	else if( nForceHeight != 0) {
		dfYRes = (dfMaxY - dfMinY) / nForceHeight;
		dfXRes = dfYRes;

		adfDstGeoTransform[0] = dfMinX;
		adfDstGeoTransform[3] = dfMaxY;
		adfDstGeoTransform[1] = dfXRes;
		adfDstGeoTransform[5] = -dfYRes;

		nPixels = (int) ((dfMaxX - dfMinX + (dfXRes/2.0)) / dfXRes);
		nLines = nForceHeight;
	}

	/* --------------------- Create the output --------------------------- */
	hDstDS = GDALCreate( hDriver, "mem", nPixels, nLines, 
			GDALGetRasterCount(hSrcDS), (GDALDataType)typeCLASS, NULL );
    
	CPLAssert( hDstDS != NULL );

	/* -------------- Write out the projection definition ---------------- */
	GDALSetProjection( hDstDS, pszDstWKT );
	GDALSetGeoTransform( hDstDS, adfDstGeoTransform );

	/* --------------------- Setup warp options -------------------------- */
	GDALWarpOptions *psWO = GDALCreateWarpOptions();

	psWO->hSrcDS = hSrcDS;
	psWO->hDstDS = hDstDS;

	psWO->nBandCount = nBands;
	psWO->panSrcBands = (int *) CPLMalloc(psWO->nBandCount * sizeof(int) );
	psWO->panDstBands = (int *) CPLMalloc(psWO->nBandCount * sizeof(int) );
	for( i = 0; i < nBands; i++ ) {
		psWO->panSrcBands[i] = i+1;
		psWO->panDstBands[i] = i+1;
	}

	if( dfWarpMemoryLimit != 0.0 )
		psWO->dfWarpMemoryLimit = dfWarpMemoryLimit;

	/* --------------------- Setup the Resampling Algo ------------------- */
	psWO->eResampleAlg = interpMethod;


	/* --------------------- Setup NODATA options ------------------------ */
	papszWarpOptions = CSLSetNameValue(papszWarpOptions, "INIT_DEST", "NO_DATA" );

	if ( pdfDstNodata == NULL && (typeCLASS == GDT_Float32 || typeCLASS == GDT_Float64) ) {
		pdfDstNodata = (double *) mxCalloc((size_t)1, sizeof(double));
		*pdfDstNodata = mxGetNaN();
	}
	else if (pdfDstNodata != NULL) {
#define CLAMP(val,type,minval,maxval) \
    do { if (val < minval) { val = minval; } \
    else if (val > maxval) { val = maxval; } \
    else if (val != (type)val) { val = (type)(val + 0.5); } } \
    while(0)
		switch( typeCLASS ) {
			case GDT_Byte:
				CLAMP(pdfDstNodata[0], GByte, 0.0, 255.0);
				break;
			case GDT_UInt16:
				CLAMP(pdfDstNodata[0], GInt16, -32768.0, 32767.0);
				break;
			case GDT_Int16:
				CLAMP(pdfDstNodata[0], GUInt16, 0.0, 65535.0);
				break;
			case GDT_UInt32:
				CLAMP(pdfDstNodata[0], GInt32, -2147483648.0, 2147483647.0);
				break;
			case GDT_Int32:
				CLAMP(pdfDstNodata[0], GUInt32, 0.0, 4294967295.0);
				break;
			default:
				break;
		}
	}

	psWO->papszWarpOptions = CSLDuplicate(papszWarpOptions);

	if (pdfDstNodata != NULL) {
		psWO->padfDstNoDataReal = (double *) CPLMalloc(psWO->nBandCount*sizeof(double));
		psWO->padfDstNoDataImag = (double *) CPLMalloc(psWO->nBandCount*sizeof(double));
		for (i = 0; i < nBands; i++) {
                        psWO->padfDstNoDataReal[i] = pdfDstNodata[0];
                        psWO->padfDstNoDataImag[i] = 0.0;
			GDALSetRasterNoDataValue( GDALGetRasterBand(hDstDS, i+1), pdfDstNodata[0]);
		}
	}

	/* ------------ Establish reprojection transformer ------------------- */
	psWO->pTransformerArg = GDALCreateGenImgProjTransformer( hSrcDS, GDALGetProjectionRef(hSrcDS), 
							hDstDS, GDALGetProjectionRef(hDstDS), 
							nGCPCount == 0 ? FALSE : TRUE, 0.0, nOrder );
	psWO->pfnTransformer = GDALGenImgProjTransform;

	/* ----------- Initialize and execute the warp operation ------------- */
	GDALWarpOperation oOperation;

	oOperation.Initialize( psWO );
	eErr = oOperation.ChunkAndWarpImage( 0, 0, GDALGetRasterXSize( hDstDS ),
						GDALGetRasterYSize( hDstDS ) );
	CPLAssert( eErr == CE_None );

	GDALDestroyGenImgProjTransformer( psWO->pTransformerArg );
	GDALDestroyWarpOptions( psWO );
	GDALClose( hSrcDS );

	/* ------------ Free memory used to fill the hSrcDS dataset ---------- */
	switch( typeCLASS ) {
		case GDT_Byte:		mxFree((void *)outByte);	break;
		case GDT_UInt16:	mxFree((void *)outUI16);	break; 
		case GDT_Int16:		mxFree((void *)outI16);		break; 
		case GDT_UInt32:	mxFree((void *)outUI32);	break; 
		case GDT_Int32:		mxFree((void *)outI32);		break; 
		case GDT_Float32:	mxFree((void *)outF32);		break; 
		case GDT_Float64:	mxFree((void *)outF64);		break; 
	}

	int out_dims[3];
	out_dims[0] = nLines;
	out_dims[1] = nPixels;
	out_dims[2] = nBands;
	plhs[0] = mxCreateNumericArray (n_dims,out_dims,mxGetClassID(prhs[0]), mxREAL);
	tmp = (char *)mxCalloc(nPixels * nLines, nBytes);

	/* ------ Allocate memory to be used in filling the hDstDS dataset ---- */
	switch( typeCLASS ) {
		case GDT_Byte:
			outByte = (unsigned char *)mxGetData(plhs[0]);		break;
		case GDT_UInt16:
			outUI16 = (unsigned short int *)mxGetData(plhs[0]);	break;
		case GDT_Int16:
			outI16 = (short int *)mxGetData(plhs[0]);		break;
		case GDT_UInt32:
			outUI32 = (unsigned int *)mxGetData(plhs[0]);		break;
		case GDT_Int32:
			outI32 = (int *)mxGetData(plhs[0]);			break;
		case GDT_Float32:
			outF32 = (float *)mxGetData(plhs[0]);			break;
		case GDT_Float64:
			outF64 = (double *)mxGetData(plhs[0]);			break;
	}

	/* ----------- Copy the output hSrcDS dataset data into plhs  ---------- */
	for (i = 1; i <= nBands; i++) {
		hBand = GDALGetRasterBand( hDstDS, i ); 
		GDALRasterIO( hBand, GF_Read, 0, 0, nPixels, nLines, tmp, nPixels, nLines,
				(GDALDataType)typeCLASS, 0, 0 );
		nXYSize = (i-1) * nPixels * nLines;
		switch( typeCLASS ) {
			case GDT_Byte:
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outByte[m + n*nLines + nXYSize] = tmp[c++];
				break;
			case GDT_UInt16:
				tmpUI16 = (GUInt16 *) tmp;
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outUI16[m + n*nLines + nXYSize] = tmpUI16[c++];
				break;
			case GDT_Int16:
				tmpI16 = (GInt16 *) tmp;
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outI16[m + n*nLines + nXYSize] = tmpI16[c++];
				break;
			case GDT_UInt32:
				tmpUI32 = (GUInt32 *) tmp;
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outUI32[m + n*nLines + nXYSize] = tmpUI32[c++];
				break;
			case GDT_Int32:
				tmpI32 = (GInt32 *) tmp;
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outI32[m + n*nLines + nXYSize] = tmpI32[c++];
				break;
			case GDT_Float32:
				tmpF32 = (float *) tmp;
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outF32[m + n*nLines + nXYSize] = tmpF32[c++];
				break;
			case GDT_Float64:
				tmpF64 = (double *) tmp;
				for (m = nLines-1, c = 0; m >= 0; m--) for (n = 0; n < nPixels; n++)
					outF64[m + n*nLines + nXYSize] = tmpF64[c++];
				break;
		}
	}

	mxFree(tmp);
	if (nGCPCount) {
		GDALDeinitGCPs( nGCPCount, pasGCPs );	/* makes this mex crash in the next call - Is it still true??? */
		mxFree((void *) pasGCPs );
	}

	if (nlhs == 2)
		plhs[1] = populate_metadata_struct (hDstDS, 1);

	runed_once = TRUE;	/* Signals that next call won't need to call GDALAllRegister() again */

	/*GDALDestroyDriverManager();
	OGRFree(pszDstWKT);*/
	GDALClose( hDstDS );
	CSLDestroy( papszWarpOptions );
	if (pszDstWKT && strlen(pszDstWKT) > 1 ) OGRFree(pszDstWKT);	
	if (pszSrcWKT && strlen(pszSrcWKT) > 1 ) OGRFree(pszSrcWKT);
}
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    // ****************   PARSE THE INPUTS  ******************* //
    myAssert(nrhs==4,"fitStumpUINT8_c: bad nrhs");
    const mxArray* mxX = prhs[0];
    myAssert(mxIsUint8(mxX), "fitStumpUINT8_c: X must be uint8");
    unsigned char* X = (unsigned char*) mxGetPr(mxX);
    int N = mxGetM(mxX);    int p = mxGetN(mxX);
    
    const mxArray* mxWWY = prhs[1];
    myAssert(mxIsDouble(prhs[1]), "fitStumpUINT8_c: wwy must be double");
    double* wwy = (double*) mxGetPr(mxWWY);
    myAssert(mxGetM(mxWWY)==2, "fitStumpUINT8_c: wwy must be 2 x N");
    myAssert(mxGetN(mxWWY)==N, "fitStumpUINT8_c: wwy must be 2 x N");
    const mxArray* mxCandVars = prhs[2];
    myAssert(mxIsUint32(mxCandVars), "fitStumpUINT8_c: mxCandVars must be uint32");
    unsigned int* candVars = (unsigned int*) mxGetPr(mxCandVars);
    int nCand = mxGetNumberOfElements(mxCandVars);
    
    const mxArray* mxGoodInd = prhs[3];
    int nGd = mxGetNumberOfElements(mxGoodInd);
    myAssert(nGd==0 || mxIsUint32(mxGoodInd), "fitStumpUINT8_c: mxGoodInd must be uint32");
    unsigned int* goodInd = (unsigned int*) mxGetPr(mxGoodInd);
        
    // ******************  SET UP THE OUTPUTS  ******************* //
    plhs[0] = mxCreateNumericMatrix(1,nCand,mxINT32_CLASS,mxREAL);
    int* cutInd = (int*) mxGetPr(plhs[0]);
	plhs[1] = mxCreateNumericMatrix(1,nCand,mxDOUBLE_CLASS, mxREAL);
    double* ssxBest = (double*) mxGetPr(plhs[1]);
	plhs[2] = mxCreateNumericMatrix(1,nCand,mxDOUBLE_CLASS,mxREAL);
	double* muL = (double*) mxGetPr(plhs[2]);
	plhs[3] = mxCreateNumericMatrix(1,nCand,mxDOUBLE_CLASS,mxREAL);
    double* muR = (double*) mxGetPr(plhs[3]);
    // ************** MAIN LOOP OVER ALL CANDIDATE VARS *********** //
    for(int m=0; m<nCand; m++) {
        unsigned char* x = X + N*candVars[m];
        double* wwyBuck = (double *) mxMalloc(2*256*sizeof(double));
        // fill weights with small epsilon for numerical stability
        for(int i=0; i<256; i++) {
            wwyBuck[i*2] = 1.0E-10;
            wwyBuck[i*2+1] = 0;
        }
        // make weighted histogram of w and wy
        buckSums(wwyBuck, wwy, N, x, goodInd, nGd);
        // cumsum
        __m128d* wwyBuck128 = (__m128d*) wwyBuck;
        for(int i=1; i<256; i++)
            wwyBuck128[i] = _mm_add_pd(wwyBuck128[i], wwyBuck128[i-1]);
        // compute -ssx
        __m128d wCumEnd = _mm_set_pd(wwyBuck[256*2-2], wwyBuck[256*2-2]);
        __m128d wyCumEnd = _mm_set_pd(wwyBuck[256*2-1], wwyBuck[256*2-1]);

        __m128d* ssx128 = (__m128d*) mxMalloc(1*256*sizeof(__m128d));
        for(int i=0; i<128; i++) {
            __m128d wwyBuck1 = wwyBuck128[i*2];
            __m128d wwyBuck2 = wwyBuck128[i*2+1];
            __m128d wyBuck = _mm_unpackhi_pd(wwyBuck1,wwyBuck2);
            __m128d wBuck = _mm_unpacklo_pd(wwyBuck1,wwyBuck2);
            ssx128[i] = _mm_div_pd(_mm_mul_pd(wyBuck,wyBuck),wBuck);

            __m128d tmp1 = _mm_sub_pd(wyCumEnd,wyBuck);
            tmp1 = _mm_mul_pd(tmp1,tmp1);
            __m128d tmp2 = _mm_sub_pd(wCumEnd,wBuck);

            ssx128[i] = _mm_add_pd(ssx128[i],_mm_div_pd(tmp1,tmp2));
        }
        // find best split location for this candidate variable
        double* ssx = (double*) ssx128;
        double mx = ssx[0];     cutInd[m] = 0;
        
        for(int i=1;i<256;i++) {
            if(ssx[i] > mx) {
                mx = ssx[i];	cutInd[m] = i;
            }
        }
        ssxBest[m] = -mx;
        muL[m] = wwyBuck[cutInd[m]*2+1] / wwyBuck[cutInd[m]*2];
        muR[m] = (wwyBuck[256*2-1] - wwyBuck[cutInd[m]*2+1]) / (wwyBuck[256*2-2] - wwyBuck[cutInd[m]*2]);
    }
}
Ejemplo n.º 24
0
//-------------------------------------------------------------------
void mexFunction(int POutputCount,  mxArray* POutput[], int PInputCount, const mxArray *PInputs[])
{
    	const int	*SZ;	    
    	double* 	LInput;
    	double* 	LInputI;
    	double* 	LOutputSum;
    	double* 	LOutputSumI;
    	double* 	LOutputCount;
    	double* 	LOutputSum2;
    	double* 	LOutputSum4;
    	double  	x, x2;
    	unsigned long   LCount, LCountI;
    	double  	LSum, LSum2, LSum4;

    	unsigned	DIM = 0; 
    	unsigned long	D1, D2, D3; 	// NN; 	//  	
    	unsigned    	ND, ND2;	// number of dimensions: input, output
    	unsigned long	ix1, ix2;	// index to input and output
    	unsigned    	j, k, l;	// running indices 
    	int 		*SZ2;		// size of output 	    


	// check for proper number of input and output arguments
	if ((PInputCount <= 0) || (PInputCount > 2))
	        mexErrMsgTxt("SumSkipNan.MEX requires 1 or 2 arguments.");
	if (POutputCount > 4)
	        mexErrMsgTxt("SumSkipNan.MEX has 1 to 4 output arguments.");

	// get 1st argument
	if(mxIsDouble(PInputs[0]))
		LInput  = mxGetPr(PInputs[0]);
	else 	
		mexErrMsgTxt("First argument must be DOUBLE.");

	if(mxIsLogical(PInputs[0]))
		LInput  = (double*)mxGetLogicals(PInputs[0]);
	else if(mxIsNumeric(PInputs[0]))
		LInput  = mxGetPr(PInputs[0]);
	else if(mxIsSparse(PInputs[0]))
		LInput  = mxGetPr(PInputs[0]);
	else if(mxIsInt8(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsUint8(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsInt16(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsUint16(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsInt32(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else if(mxIsUint32(PInputs[0]))
		LInput  = (double *)mxGetData(PInputs[0]);
	else
		mexErrMsgTxt("First argument must be NUMERIC.");

	if(mxIsComplex(PInputs[0]))
		LInputI = mxGetPi(PInputs[0]);
	if(mxIsComplex(PInputs[0]) & (POutputCount > 3))
	        mexErrMsgTxt("More than 3 output arguments only supported for REAL data ");

    	// get 2nd argument
    	if  (PInputCount == 2){
 	       	switch (mxGetNumberOfElements(PInputs[1])) {
		case 0: x = 0.0; 		// accept empty element
			break;
		case 1: x = (mxIsNumeric(PInputs[1]) ? mxGetScalar(PInputs[1]) : -1.0); 
			break;
		default:x = -1.0;		// invalid 
		}
		if ((x < 0) || (x > 65535) || (x != floor(x))) 
			mexErrMsgTxt("Error SUMSKIPNAN.MEX: DIM-argument must be a positive integer scalar");

		DIM = (unsigned)floor(x);	
	}

	// get size 
    	ND = mxGetNumberOfDimensions(PInputs[0]);	
    	// NN = mxGetNumberOfElements(PInputs[0]);
    	SZ = mxGetDimensions(PInputs[0]);		

	// if DIM==0 (undefined), look for first dimension with more than 1 element. 
	for (k = 0; (DIM < 1) && (k < ND); k++) 
		if (SZ[k]>1) DIM = k+1;
	
	if (DIM < 1) DIM=1;		// in case DIM is still undefined 

	ND2 = (ND>DIM ? ND : DIM);	// number of dimensions of output 

	SZ2 = (int*)mxCalloc(ND2, sizeof(int)); // allocate memory for output size

	for (j=0; j<ND; j++)		// copy size of input;  
		SZ2[j] = SZ[j]; 	
	for (j=ND; j<ND2; j++)		// in case DIM > ND, add extra elements 1 
		SZ2[j] = 1; 	

    	for (j=0, D1=1; j<DIM-1; D1=D1*SZ2[j++]); 	// D1 is the number of elements between two elements along dimension  DIM  
	D2 = SZ2[DIM-1];		// D2 contains the size along dimension DIM 	
    	for (j=DIM, D3=1;  j<ND; D3=D3*SZ2[j++]); 	// D3 is the number of blocks containing D1*D2 elements 

	SZ2[DIM-1] = 1;		// size of output is same as size of input but SZ(DIM)=1;

	    // create outputs
	#define TYP mxDOUBLE_CLASS

	if(mxIsComplex(PInputs[0]))
	{	POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxCOMPLEX);
		LOutputSum = mxGetPr(POutput[0]);
		LOutputSumI= mxGetPi(POutput[0]);
    	}
	else 
	{	POutput[0] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
		LOutputSum = mxGetPr(POutput[0]);
    	}

    	if (POutputCount >= 2){
		POutput[1] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
        	LOutputCount = mxGetPr(POutput[1]);
    	}
    	if (POutputCount >= 3){
		POutput[2] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
        	LOutputSum2  = mxGetPr(POutput[2]);
    	}
    	if (POutputCount >= 4){
		POutput[3] = mxCreateNumericArray(ND2, SZ2, TYP, mxREAL);
        	LOutputSum4  = mxGetPr(POutput[3]);
    	}

	mxFree(SZ2);

	// OUTER LOOP: along dimensions > DIM
	for (l = 0; l<D3; l++) 	
    	{
		ix2 =   l*D1;	// index for output 
		ix1 = ix2*D2;	// index for input 

		// Inner LOOP: along dimensions < DIM
		for (k = 0; k<D1; k++, ix1++, ix2++) 	
		{
		        LCount = 0;
			LSum   = 0.0;
			LSum2  = 0.0;
			LSum4  = 0.0;
	        	    		
			// LOOP  along dimension DIM
	    		for (j=0; j<D2; j++) 	
			{
				x = LInput[ix1 + j*D1];
        	        	if (!mxIsNaN(x))
				{
					LCount++; 
					LSum += x; 
					x2 = x*x;
					LSum2 += x2; 
					LSum4 += x2*x2; 
				}
			}
			LOutputSum[ix2] = LSum;
            		if (POutputCount >= 2)
                		LOutputCount[ix2] = (double)LCount;
            		if (POutputCount >= 3)
                		LOutputSum2[ix2] = LSum2;
            		if (POutputCount >= 4)
                		LOutputSum4[ix2] = LSum4;

			if(mxIsComplex(PInputs[0]))
			{
				LSum = 0.0;	
	    			LCountI = 0;
				LSum2  = 0.0;
				for (j=0; j<D2; j++) 	
				{
					x = LInputI[ix1 + j*D1];
        	        		if (!mxIsNaN(x))
					{
						LCountI++; 
						LSum  += x; 
						LSum2 += x*x; 
					}
				}
				LOutputSumI[ix2] = LSum;
				if (LCount != LCountI)
			            	mexErrMsgTxt("Number of NaNs is different for REAL and IMAG part");
	            		if (POutputCount >= 3)
        	        		LOutputSum2[ix2] += LSum2;
			}
		}
	}
}
Ejemplo n.º 25
0
void mexFunction(
    int nargout,
    mxArray *out[],
    int nargin,
    const mxArray *in[]) {

    /* declare variables */
    int nr, nc;
    register unsigned int index_ij, index_ik, index_jk;
	register unsigned int i, j, k;
    mxLogical *segms;
    unsigned int *sp_seg_szs;
    unsigned int *intersections, *reunions;
    float *o;
    
    /* check argument */
    if (nargin<1) {
        mexErrMsgTxt("One input argument required ( the segments in column form )");
    }
    if (nargout>1) {
        mexErrMsgTxt("Too many output arguments");
    }

    nr = mxGetM(in[0]);
    nc = mxGetN(in[0]);

    if (!mxIsLogical(in[0]) || mxGetNumberOfDimensions(in[0]) != 2) {
        mexErrMsgTxt("Usage: segms must be a logical matrix");
    }
    
    segms = (bool *) mxGetData(in[0]);
    intersections = (unsigned int *)malloc(nc* nc*sizeof(unsigned int));
    reunions = (unsigned int *)malloc(nc* nc*sizeof(unsigned int));
    
    /* if the user provided the SP areas */
    if (nargin == 2) { 
        if (!mxIsUint32(in[1]) || mxGetNumberOfElements(in[1]) != nr) {
            mexErrMsgTxt("Usage: the second (optional) argument should give the weight/area of each superpixel in uint32 and the number of elements should be same # of rows as first argument.");
        }
        sp_seg_szs = (unsigned int*) mxGetData(in[1]);
    }
    
    if (intersections==NULL || reunions == NULL) {
        mexErrMsgTxt("Not enough memory");
    }
    
    out[0] = mxCreateNumericMatrix(nc,nc,mxSINGLE_CLASS, (mxComplexity) 0);
    if (out[0]==NULL) {
	    mexErrMsgTxt("Not enough memory for the output matrix");
    }
    o = (float *) mxGetPr(out[0]);

  	/*clock_t begin=clock();*/
    /* intersections and reunions */
/*
    #pragma omp parallel for
    for(i=0; i<nc; i++) {
        for(j=i+1; j<nc; j++) {
            index_ij = i*nc + j;
            intersections[index_ij] = 0;
            reunions[index_ij] = 0;            
            
            for( k=0; k<nr; k++) {
                index_ik = i*nr + k;
                index_jk = j*nr + k;
                intersections[index_ij] = intersections[index_ij] + (segms[index_ik] * segms[index_jk]);
                reunions[index_ij] = reunions[index_ij] + (segms[index_ik] | segms[index_jk]);
            }
        }
    }
*/
    if (nargin == 2) {
        overlap_sp(intersections, reunions, segms, sp_seg_szs, nc, nr);
    } else {
        overlap(intersections, reunions, segms, nc, nr);
    }

   /*clock_t end=clock();
    double diffms=((end - begin)*1000)/CLOCKS_PER_SEC;
    mexPrintf("time taken in main loop: %f\n", diffms);*/
    
    /* computation of overlap, for lower triangle */
    for (i=0; i<nc; i++) {
        for(j=i+1; j<nc; j++) {             
            index_ij = i*nc+j;
//            mexPrintf("Reunions: %d \n",reunions[index_ij]);
            o[j*nc+i] = o[index_ij] = (float) intersections[index_ij] / reunions[index_ij];            
        }
    }
    free(intersections);
	free(reunions);
    intersections = reunions = 0;
    /* fill diagonal with ones */
    for (i=0; i<nc; i++) {
       o[i*nc+i] = 1;
    }
        
/*
    for(i=0;i<nc; i++) {
        for (j=0;j<nr; j++) {
            mexPrintf("o(i,j): %f\n", o[i*nc+j]);
        }
    }
*/

}
Ejemplo n.º 26
0
/* Convert a Matlab graph structure into the graph object. --sn
 */
void Graph::read (const mxArray* graph)
{
	mxArray* nodelabels = mxGetField (graph, 0, "nodelabels");
	mxArray* edges = mxGetField (graph, 0, "edges");

	if (nodelabels == NULL || edges == NULL) {
		mexPrintf ("Graph structures are missing the \"nodelabels\" "
			"or \"edges\" fields.\n");

		return;
	}

	if (mxIsUint32 (nodelabels) == 0 || mxIsUint32 (edges) == 0) {
		mexPrintf ("\"nodelabels\" or \"edges\" not of type Uint32.\n");

		return;
	}

	uint32_T* nmat = (uint32_T*) mxGetData (nodelabels);
	assert (nmat != NULL);
	unsigned int nodes = mxGetM (nodelabels);
	this->resize (nodes);
	for (unsigned int i = 0 ; i < nodes ; ++i) {
		(*this)[i].label = nmat[i];
#ifdef	DEBUG
		mexPrintf ("inserting node %d with label %d\n", i, nmat[i]);
#endif
	}

	/* emat is column organised.
	 */
	unsigned int edgecount = mxGetM (edges);
	if (edgecount > 0) {
		uint32_T* emat = (uint32_T*) mxGetData (edges);
#ifdef	DEBUG
		mexPrintf ("edges M, N: %d, %d\n", mxGetM (edges), mxGetN (edges));
#endif
		assert (emat != NULL);

		for (unsigned int i = 0 ; i < edgecount ; ++i) {
			unsigned int from = emat[i+0*edgecount] - 1;	// index correction
			unsigned int to = emat[i+1*edgecount] - 1;	// index correction
			unsigned int elabel = emat[i+2*edgecount];

			assert (from < nodes && to < nodes);
			if (from >= nodes || to >= nodes) {
				mexErrMsgTxt ("Edge from/to indices out of bounds.");
				return;
			}

			/* Warning: this makes edges undirected, which is not what we want (or
			 * do we?).
			 */
	#ifdef	DEBUG
			mexPrintf ("inserting edge from %d to %d, label %d\n",
				from, to, elabel);
	#endif
			(*this)[from].push (from, to, elabel);
			if (directed == false) {
	#ifdef	DEBUG
				mexPrintf ("  reverse: inserting edge from %d to %d, label %d\n",
					to, from, elabel);
	#endif
				(*this)[to].push (to, from, elabel);
			}
		}
	}
	buildEdge ();
}
Ejemplo n.º 27
0
void mexFunction(
    int nargout,
    mxArray *out[],
    int nargin,
    const mxArray *in[]
)
{
    /* declare variables */
    int my_count,prev_ind1,prev_ind2,ind1,ind2,cur_r1,cur_c1,cur_r2,cur_c2;
    int cond, num_pairs,cur_j,cur_i,x1,y1,x2,y2;
    int nr, nc, np, total;
    int dy,dx,i, j, k, ix, iy, jx, jy, ii, jj, iip1, jjp1, iip2, jjp2, step;
    double thresh, sigma, di, dj, a, z, maxori, phase1, phase2, slope;
// 	int *ir, *jc;
    mwIndex*ir,*jc;
	unsigned int *pi, *pj;
	double *emag, *ephase, *w;
    
    /* check argument */
    if (nargin<4) {
        mexErrMsgTxt("Four input arguments required");
    }
    if (nargout>1) {
        mexErrMsgTxt("Too many output arguments");
    }

    //printf("51\n");

    /* get edgel information */
	nr = mxGetM(in[0]);
	nc = mxGetN(in[0]);
	if ( nr*nc ==0 || nr != mxGetM(in[1]) || nc != mxGetN(in[1]) ) {
	    mexErrMsgTxt("Edge magnitude and phase shall be of the same image size");
	}
    emag = mxGetPr(in[0]);
    ephase = mxGetPr(in[1]);
    np = nr * nc;
  
    //printf("63\n");

    /* get new index pair */
    if (!mxIsUint32(in[2]) | !mxIsUint32(in[3])) {
        mexErrMsgTxt("Index pair shall be of type UINT32");
    }

    num_pairs=mxGetM(in[2]);


    //printf("73\n");

    pi = (unsigned int*)mxGetData(in[2]);
    pj = (unsigned int*)mxGetData(in[3]);    

    //printf("78\n");

    /* create output */
    //out[0] = mxCreateSparse(np,np,num_pairs,mxREAL);
    out[0] = mxCreateDoubleMatrix(num_pairs,1,mxREAL);


    //printf("85\n");

    if (out[0]==NULL) {
	    mexErrMsgTxt("Not enough memory for the output matrix");
	}
	w = mxGetPr(out[0]);


	//printf("93\n");

	//ir = mxGetIr(out[0]);
	//jc = mxGetJc(out[0]);
	
    /* find my sigma */
	/*if (nargin<5) {
	    sigma = 0;
    	for (k=0; k<np; k++) { 
    	    if (emag[k]>sigma) { sigma = emag[k]; }
    	}
	printf("104\n");
    	sigma = sigma / 6;
    	printf("sigma = %6.5f",sigma);
	} else {
	    sigma = mxGetScalar(in[4]);
	}
	a = 0.5 / (sigma * sigma);
	*/

    /* computation */ 
    thresh=0.5*255;
    cond=0;
    total = 0;
    my_count=0;

    //printf("118\n");
    for (j=0; j<num_pairs; j++) {            
    //for (j=392; j<393; j++) {            

	if ( j % 100000==0){
	    printf("Iter %d / %d\n",j,num_pairs);
	}
        //jc[j] = total;

	cur_j=pj[j];
	cur_i=pi[j];

        jx = cur_j / nr; /* col */
        jy = cur_j % nr-1; /* row */
	if (jy==-1){
	   jy=nr-1;
	   jx--;
	}
        
	ix = cur_i / nr; /* col */
        iy = cur_i % nr-1; /* row */
	if (iy==-1){
	   iy=nr-1;
	   ix--;
	}

	//printf("%d %d %d %d %d %d\n",cur_j,jx,jy,cur_i,ix,iy);
	//exit(1);

        if (jy<iy){
	    if (jx>ix){
	       y2=jy;
	       x2=jx;
	       y1=iy;
	       x1=ix;
	    }else{
	       y2=jy;
	       x2=ix;
	       y1=iy;
	       x1=jx;
	    }

        }else{

	   if (jx>ix){
	       y2=iy;
	       x2=jx;
	       y1=jy;
	       x1=ix;
	   }else{
	       y2=iy;
	       x2=ix;
	       y1=jy;
	       x1=jx;
	   }
	}

        //for (k=pj[j]; k<pj[j+1]; k++) {
        
	    maxori = 0.;

            if (cur_i==cur_j) {
                maxori = 1;
            
            } else {

                /* scan */            
                dx = (double) (x2 - x1);
                dy = (double) (y1 - y2);
            
                maxori = 0.;
	               
                
              	//iip1 = y2;
            	//jjp1 = x1;
		//jjp2 = x2;
		//iip2 = y1;
		
	
	               
		//walking along the columns on fixed y
	        for (ii=0;ii<=abs(dx);ii++){
			    z=0;
			    cur_r1=y2;
			    cur_c1=x1+ii;

			    cur_r2=y1;
			    cur_c2=x2-ii;



			    ind1=cur_r1+cur_c1*nr-1;
			    ind2=cur_r2+cur_c2*nr-1;

			    /*if (ii>0){
			       prev_ind1=cur_r1+(cur_c1+ii-1)*nr;
			       prev_ind2=cur_r2+(cur_c2-ii+1)*nr;
			    }else{
			       prev_ind1=0;
			       prev_ind2=0;
			    }*/

			    //printf("%d %d %d %d %d %d\n",ind1,cur_c1,cur_r1,ind2,cur_c2,cur_r2);
         
			    if (1){
		   	    //if (ii==0 || ephase[ind1]!=ephase[prev_ind1]){	    
	                        z = emag[ind1]; 	
				//z=emag[cur_c1+cur_r1*nc];
				
				if (z > maxori){
				    //printf("In 1\n");
	                            maxori = z;
	                        }
				//printf("%f %f\n",z,maxori);

			    }


			    if (1){
		   	    //if (ii==0 || ephase[ind2]!=ephase[prev_ind2]){
				z=emag[ind2];
				//z=emag[cur_c2+cur_r2*nc];
				//printf("index =%d\n",ind2);
				//printf("emag %f, z %f Diff %f\n",emag[ind2],z,z-maxori);

				if (z > maxori){
				    //printf("In 2\n");
	                            maxori = z;
	                        }
				//printf("%f %f\n",z,maxori);
			    }

	        }
	         
		//printf("######\n");

		//walking along the rows on fixed x
		for (ii=0;ii<=abs(dy);ii++){
			    cur_r1=y2+ii;
			    cur_c1=x1;

			    cur_r2=y1-ii;
			    cur_c2=x2;
			
			    ind1=cur_r1+cur_c1*nr-1;
			    ind2=cur_r2+cur_c2*nr-1;


			    /*if (ii>0){
			       prev_ind1=cur_r1+(cur_c1+ii-1)*nr;
			       prev_ind2=cur_r2+(cur_c2-ii+1)*nr;
			    }else{
			       prev_ind1=0;
			       prev_ind2=0;
			    }*/

			    if (1){
			    //if (ii==0 || ephase[ind1]!=ephase[prev_ind1]){
			        z = emag[ind1]; 	     
				//z = emag[cur_c1+cur_r1*nc]; 	 
			
			    	if (z > maxori){
				    //printf("In 3\n");
	                            maxori = z;
	                        }
				//printf("%f %f\n",z,maxori);
			    }
 		
			    if (1){
			    //if (ii==0 || ephase[ind2]!=ephase[prev_ind2]){
				z=emag[ind2];
				//z=emag[cur_c2+cur_r2*nc];
				if (z > maxori){
				    //printf("In 4\n");
	                            maxori = z;
	                        }
				//printf("%f %f\n",z,maxori);
			    }
	                  
	                   
	        }

		/*if (ephase[cur_i-1]!=ephase[cur_j-1] && maxori==1){
			printf("False positive True: Not Similar\n");
			printf("%d %d %d %d %d %d %f\n",cur_i-1,ix,iy,cur_j-1,jx,jy,maxori);
		}

		if (ephase[cur_i-1]==ephase[cur_j-1] && maxori<0.99){
			printf("False Negative True: Similar\n");
			printf("%d %d %d %d %d %d %f\n",cur_i-1,ix,iy,cur_j-1,jx,jy,maxori);
		}*/

		//printf("Max Ori=%f\n",maxori);
		if (maxori>thresh){
			maxori=0.1;
			my_count++;
		}else{
			maxori=1;
		}

		/*if (jy>90 || iy >90){
			printf("%d %d %d %d %d %d %f\n",cur_i,ix,iy,cur_j,jx,jy,maxori);
			maxori=1;
		}*/

                //maxori = 0.5 * maxori;
                //maxori = exp(-maxori * maxori * a);
            }       
		    //ir[total] = i;

		    w[total] = maxori;
		    //printf("Max Ori=%f\n",maxori);
		    total = total + 1;
			
	//} /* i */
    } /* j */

    printf("My count = %d\n",my_count);
        
    //jc[np] = total;
}  
Ejemplo n.º 28
0
static void get_map_dat(int i, const mxArray *ptr, MAPTYPE *maps)
{
    mxArray *tmp;
    double *pr;
    int num_dims, j, t, dtype = 0;
    const mwSize *dims;
    unsigned char *dptr;

    tmp=mxGetField(ptr,i,"dat");
    if (tmp == (mxArray *)0)
    {
        free_maps(maps,i);
        mexErrMsgTxt("Cant find dat.");
    }
    if      (mxIsDouble(tmp)) dtype = SPM_DOUBLE;
    else if (mxIsSingle(tmp)) dtype = SPM_FLOAT;
    else if (mxIsInt32 (tmp)) dtype = SPM_SIGNED_INT;
    else if (mxIsUint32(tmp)) dtype = SPM_UNSIGNED_INT;
    else if (mxIsInt16 (tmp)) dtype = SPM_SIGNED_SHORT;
    else if (mxIsUint16(tmp)) dtype = SPM_UNSIGNED_SHORT;
    else if (mxIsInt8  (tmp)) dtype = SPM_SIGNED_CHAR;
    else if (mxIsUint8 (tmp)) dtype = SPM_UNSIGNED_CHAR;
    else
    {
        free_maps(maps,i);
        mexErrMsgTxt("Unknown volume datatype.");
    }
    dptr  = (unsigned char *)mxGetPr(tmp);

    num_dims = mxGetNumberOfDimensions(tmp);
    if (num_dims > 3)
    {
        free_maps(maps,i);
        mexErrMsgTxt("Too many dimensions.");
    }
    dims     = mxGetDimensions(tmp);
    for(j=0; j<num_dims; j++)
        maps[i].dim[j]=dims[j];
    for(j=num_dims; j<3; j++)
        maps[i].dim[j]=1;
    tmp=mxGetField(ptr,i,"dim");
    if (tmp != (mxArray *)0)
    {
        if (mxGetM(tmp)*mxGetN(tmp) != 3)
        {
            free_maps(maps,i);
            mexErrMsgTxt("Wrong sized dim.");
        }
        pr = mxGetPr(tmp);
        if (maps[i].dim[0] != (mwSize)fabs(pr[0]) ||
            maps[i].dim[1] != (mwSize)fabs(pr[1]) ||
            maps[i].dim[2] != (mwSize)fabs(pr[2]))
        {
            free_maps(maps,i);
            mexErrMsgTxt("Incompatible volume dimensions in dim.");
        }
    }
    tmp=mxGetField(ptr,i,"dt");
    if (tmp != (mxArray *)0)
    {
        if (mxGetM(tmp)*mxGetN(tmp) != 1 && mxGetM(tmp)*mxGetN(tmp) != 2)
        {
            free_maps(maps,i);
            mexErrMsgTxt("Wrong sized dt.");
        }
        pr = mxGetPr(tmp);
        if (dtype != (int)fabs(pr[0]))
        {
            free_maps(maps,i);
            mexErrMsgTxt("Incompatible datatype in dt.");
        }
    }

    maps[i].addr      = 0;
    maps[i].len       = 0;
    maps[i].dtype  = dtype;
    maps[i].data   = (void  **)mxCalloc(maps[i].dim[2],sizeof(void *));
    maps[i].scale  = (double *)mxCalloc(maps[i].dim[2],sizeof(double));
    maps[i].offset = (double *)mxCalloc(maps[i].dim[2],sizeof(double));

    t   = maps[i].dim[0]*maps[i].dim[1]*get_datasize(maps[i].dtype)/8;
    tmp = mxGetField(ptr,i,"pinfo");
    if (tmp != (mxArray *)0)
    {
        if ((mxGetM(tmp) != 2 && mxGetM(tmp) != 3) || (mxGetN(tmp) != 1 && mxGetN(tmp) != maps[i].dim[2]))
        {
            free_maps(maps,i+1);
            mexErrMsgTxt("Wrong sized pinfo.");
        }
        if (mxGetM(tmp) == 3 && mxGetPr(tmp)[2] != 0)
        {
            free_maps(maps,i+1);
            mexErrMsgTxt("pinfo(3) must equal 0 to read dat field.");
        }
        pr = mxGetPr(tmp);
        if (mxGetN(tmp) == 1)
            for(j=0; j<maps[i].dim[2]; j++)
            {
                maps[i].scale[j]  = pr[0];
                maps[i].offset[j] = pr[1];
                maps[i].data[j]   = &(dptr[j*t]);
            }
        else
            for(j=0; j<maps[i].dim[2]; j++)
            {
                maps[i].scale[j]  = pr[0+j*2];
                maps[i].offset[j] = pr[1+j*2];
                maps[i].data[j]   = &(dptr[j*t]);
            }
    }
    else
        for(j=0; j<maps[i].dim[2]; j++)
        {
            maps[i].scale[j]  = 1.0;
            maps[i].offset[j] = 0.0;
            maps[i].data[j]   = &(dptr[j*t]);
        }
    tmp=mxGetField(ptr,i,"mat");
    if (tmp != (mxArray *)0)
    {
        if (mxGetM(tmp) != 4 || mxGetN(tmp) != 4)
        {
            free_maps(maps,i+1);
            mexErrMsgTxt("Wrong sized mat.");
        }
        pr = mxGetPr(tmp);
        for(j=0; j<16; j++)
            maps[i].mat[j] = pr[j];
    }
    else
    {
        for(j=0; j<16; j++)
            maps[i].mat[j] = 0.0;
        for(j=0; j<4; j++)
            maps[i].mat[j + j*4] = 1.0;
    }
}
Ejemplo n.º 29
0
void mexFunction(
    int nargout,
    mxArray *out[],
    int nargin,
    const mxArray *in[]
)
{
    /* declare variables */
    int nr, nc, np, total;
    int i, j, k, ix, iy, jx, jy;
	int *ir, *jc;
	int squareDistance;
    /* unsigned long *pi, *pj; */
unsigned int *pi, *pj;
	double *w;

	double temp,a1,a2,wij;
	double rMin;
	double sigmaX, sigmaIntensite,valeurMinW;
	double *image;
    
    /* check argument */
    if (nargin<7) {
        mexErrMsgTxt("Four input arguments required");
    }
    if (nargout>1) {
        mexErrMsgTxt("Too many output arguments");
    }

    /* get edgel information */
	nr = mxGetM(in[0]);
	nc = mxGetN(in[0]);
    	np = nr * nc;

    image = mxGetPr(in[0]);


    
    /* get new index pair */
    if (!mxIsUint32(in[1]) | !mxIsUint32(in[2])) {
        mexErrMsgTxt("Index pair shall be of type UINT32");
    }
    if (mxGetM(in[2]) * mxGetN(in[2]) != np + 1) {
        mexErrMsgTxt("Wrong index representation");
    }
    pi = mxGetData(in[1]);
    pj = mxGetData(in[2]);    

    /* create output */
    out[0] = mxCreateSparse(np,np,pj[np],mxREAL);
    if (out[0]==NULL) {
	    mexErrMsgTxt("Not enough memory for the output matrix");
	}
	w = mxGetPr(out[0]);
	ir = mxGetIr(out[0]);
	jc = mxGetJc(out[0]);
	
	rMin = mxGetScalar(in[3]);
	sigmaX = mxGetScalar(in[4]);
	sigmaIntensite= mxGetScalar(in[5]);
	valeurMinW = mxGetScalar(in[6]);

	a1 = 1.0/ (sigmaX*sigmaX);
	a2 = 1.0 / (sigmaIntensite*sigmaIntensite );

    /* computation */ 
    total = 0;
    for (j=0; j<np; j++) {            

        jc[j] = total;
        jx = j / nr; /* col */
        jy = j % nr; /* row */
        
        for (k=pj[j]; k<pj[j+1]; k++) {
        
            i = pi[k];
          
            if (i==j) {
                wij= 1; /*voir*/
            
            } else {        
                ix = i / nr; 
                iy = i % nr;

		squareDistance = (ix-jx)*(ix-jx)+(iy-jy)*(iy-jy);
		
	           temp = image[i]-image[j];
		   wij = exp(- squareDistance * a1 - temp*temp * a2 );
		   /*if(wij < valeurMinW)
		      wij = -0.1;*/
            }
		ir[total] = i;

		w[total] = wij;
		total = total + 1;
			
	  } /* i */

    } /* j */
        
    jc[np] = total;
}