Beispiel #1
0
/*NUMPY_API
 * Clip
 */
NPY_NO_EXPORT PyObject *
PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max, PyArrayObject *out)
{
    PyArray_FastClipFunc *func;
    int outgood = 0, ingood = 0;
    PyArrayObject *maxa = NULL;
    PyArrayObject *mina = NULL;
    PyArrayObject *newout = NULL, *newin = NULL;
    PyArray_Descr *indescr = NULL, *newdescr = NULL;
    char *max_data, *min_data;
    PyObject *zero;

    /* Treat None the same as NULL */
    if (min == Py_None) {
        min = NULL;
    }
    if (max == Py_None) {
        max = NULL;
    }

    if ((max == NULL) && (min == NULL)) {
        PyErr_SetString(PyExc_ValueError,
                        "array_clip: must set either max or min");
        return NULL;
    }

    func = PyArray_DESCR(self)->f->fastclip;
    if (func == NULL
        || (min != NULL && !PyArray_CheckAnyScalar(min))
        || (max != NULL && !PyArray_CheckAnyScalar(max))) {
        return _slow_array_clip(self, min, max, out);
    }
    /* Use the fast scalar clip function */

    /* First we need to figure out the correct type */
    if (min != NULL) {
        indescr = PyArray_DescrFromObject(min, NULL);
        if (indescr == NULL) {
            goto fail;
        }
    }
    if (max != NULL) {
        newdescr = PyArray_DescrFromObject(max, indescr);
        Py_XDECREF(indescr);
        indescr = NULL;
        if (newdescr == NULL) {
            goto fail;
        }
    }
    else {
        /* Steal the reference */
        newdescr = indescr;
        indescr = NULL;
    }


    /*
     * Use the scalar descriptor only if it is of a bigger
     * KIND than the input array (and then find the
     * type that matches both).
     */
    if (PyArray_ScalarKind(newdescr->type_num, NULL) >
        PyArray_ScalarKind(PyArray_DESCR(self)->type_num, NULL)) {
        indescr = PyArray_PromoteTypes(newdescr, PyArray_DESCR(self));
        if (indescr == NULL) {
            goto fail;
        }
        func = indescr->f->fastclip;
        if (func == NULL) {
            Py_DECREF(indescr);
            return _slow_array_clip(self, min, max, out);
        }
    }
    else {
        indescr = PyArray_DESCR(self);
        Py_INCREF(indescr);
    }
    Py_DECREF(newdescr);
    newdescr = NULL;

    if (!PyDataType_ISNOTSWAPPED(indescr)) {
        PyArray_Descr *descr2;
        descr2 = PyArray_DescrNewByteorder(indescr, '=');
        Py_DECREF(indescr);
        indescr = NULL;
        if (descr2 == NULL) {
            goto fail;
        }
        indescr = descr2;
    }

    /* Convert max to an array */
    if (max != NULL) {
        Py_INCREF(indescr);
        maxa = (PyArrayObject *)PyArray_FromAny(max, indescr, 0, 0,
                                 NPY_ARRAY_DEFAULT, NULL);
        if (maxa == NULL) {
            goto fail;
        }
    }

    /*
     * If we are unsigned, then make sure min is not < 0
     * This is to match the behavior of _slow_array_clip
     *
     * We allow min and max to go beyond the limits
     * for other data-types in which case they
     * are interpreted as their modular counterparts.
    */
    if (min != NULL) {
        if (PyArray_ISUNSIGNED(self)) {
            int cmp;
            zero = PyInt_FromLong(0);
            cmp = PyObject_RichCompareBool(min, zero, Py_LT);
            if (cmp == -1) {
                Py_DECREF(zero);
                goto fail;
            }
            if (cmp == 1) {
                min = zero;
            }
            else {
                Py_DECREF(zero);
                Py_INCREF(min);
            }
        }
        else {
            Py_INCREF(min);
        }

        /* Convert min to an array */
        Py_INCREF(indescr);
        mina = (PyArrayObject *)PyArray_FromAny(min, indescr, 0, 0,
                                 NPY_ARRAY_DEFAULT, NULL);
        Py_DECREF(min);
        if (mina == NULL) {
            goto fail;
        }
    }


    /*
     * Check to see if input is single-segment, aligned,
     * and in native byteorder
     */
    if (PyArray_ISONESEGMENT(self) &&
                            PyArray_CHKFLAGS(self, NPY_ARRAY_ALIGNED) &&
                            PyArray_ISNOTSWAPPED(self) &&
                            (PyArray_DESCR(self) == indescr)) {
        ingood = 1;
    }
    if (!ingood) {
        int flags;

        if (PyArray_ISFORTRAN(self)) {
            flags = NPY_ARRAY_FARRAY;
        }
        else {
            flags = NPY_ARRAY_CARRAY;
        }
        Py_INCREF(indescr);
        newin = (PyArrayObject *)PyArray_FromArray(self, indescr, flags);
        if (newin == NULL) {
            goto fail;
        }
    }
    else {
        newin = self;
        Py_INCREF(newin);
    }

    /*
     * At this point, newin is a single-segment, aligned, and correct
     * byte-order array of the correct type
     *
     * if ingood == 0, then it is a copy, otherwise,
     * it is the original input.
     */

    /*
     * If we have already made a copy of the data, then use
     * that as the output array
     */
    if (out == NULL && !ingood) {
        out = newin;
    }

    /*
     * Now, we know newin is a usable array for fastclip,
     * we need to make sure the output array is available
     * and usable
     */
    if (out == NULL) {
        Py_INCREF(indescr);
        out = (PyArrayObject*)PyArray_NewFromDescr(Py_TYPE(self),
                                            indescr, PyArray_NDIM(self),
                                            PyArray_DIMS(self),
                                            NULL, NULL,
                                            PyArray_ISFORTRAN(self),
                                            (PyObject *)self);
        if (out == NULL) {
            goto fail;
        }

        outgood = 1;
    }
    else Py_INCREF(out);
    /* Input is good at this point */
    if (out == newin) {
        outgood = 1;
    }
    if (!outgood && PyArray_ISONESEGMENT(out) &&
                        PyArray_CHKFLAGS(out, NPY_ARRAY_ALIGNED) &&
                        PyArray_ISNOTSWAPPED(out) &&
                        PyArray_EquivTypes(PyArray_DESCR(out), indescr)) {
        outgood = 1;
    }

    /*
     * Do we still not have a suitable output array?
     * Create one, now
     */
    if (!outgood) {
        int oflags;
        if (PyArray_ISFORTRAN(out))
            oflags = NPY_ARRAY_FARRAY;
        else
            oflags = NPY_ARRAY_CARRAY;
        oflags |= NPY_ARRAY_UPDATEIFCOPY | NPY_ARRAY_FORCECAST;
        Py_INCREF(indescr);
        newout = (PyArrayObject*)PyArray_FromArray(out, indescr, oflags);
        if (newout == NULL) {
            goto fail;
        }
    }
    else {
        newout = out;
        Py_INCREF(newout);
    }

    /* make sure the shape of the output array is the same */
    if (!PyArray_SAMESHAPE(newin, newout)) {
        PyErr_SetString(PyExc_ValueError, "clip: Output array must have the"
                        "same shape as the input.");
        goto fail;
    }
    if (PyArray_DATA(newout) != PyArray_DATA(newin)) {
        if (PyArray_AssignArray(newout, newin,
                    NULL, NPY_DEFAULT_ASSIGN_CASTING) < 0) {
            goto fail;
        }
    }

    /* Now we can call the fast-clip function */
    min_data = max_data = NULL;
    if (mina != NULL) {
        min_data = PyArray_DATA(mina);
    }
    if (maxa != NULL) {
        max_data = PyArray_DATA(maxa);
    }
    func(PyArray_DATA(newin), PyArray_SIZE(newin), min_data, max_data, PyArray_DATA(newout));

    /* Clean up temporary variables */
    Py_XDECREF(indescr);
    Py_XDECREF(newdescr);
    Py_XDECREF(mina);
    Py_XDECREF(maxa);
    Py_DECREF(newin);
    /* Copy back into out if out was not already a nice array. */
    Py_DECREF(newout);
    return (PyObject *)out;

 fail:
    Py_XDECREF(indescr);
    Py_XDECREF(newdescr);
    Py_XDECREF(maxa);
    Py_XDECREF(mina);
    Py_XDECREF(newin);
    PyArray_XDECREF_ERR(newout);
    return NULL;
}
Beispiel #2
0
PyArrayObject*
PyArrayObject_Block(PyArrayObject *array, size_t start, size_t end) {
    Py_INCREF(PyArray_DESCR(array));
    npy_intp elements[1] = { end - start };
    return (PyArrayObject*) PyArray_NewFromDescr(&PyArray_Type, PyArray_DESCR(array), 1, elements, NULL, (void*)(PyArray_BYTES(array) + start * PyArray_DESCR(array)->elsize), NPY_ARRAY_CARRAY | !NPY_ARRAY_OWNDATA, NULL);
}
Beispiel #3
0
int Object_npyArrayAddItem(void *prv, JSOBJ obj, JSOBJ value)
{
  PyObject* type;
  PyArray_Descr* dtype;
  npy_intp i;
  char *new_data, *item;
  NpyArrContext* npyarr = (NpyArrContext*) obj;
  PRINTMARK();
  if (!npyarr)
  {
    return 0;
  }

  i = npyarr->i;

  npyarr->shape.ptr[npyarr->dec->curdim-1]++;

  if (PyArray_Check((PyObject*)value))
  {
    // multidimensional array, keep decoding values.
    return 1;
  }

  if (!npyarr->ret)
  {
    // Array not initialised yet.
    // We do it here so we can 'sniff' the data type if none was provided
    if (!npyarr->dec->dtype)
    {
      type = PyObject_Type(value);
      if(!PyArray_DescrConverter(type, &dtype))
      {
        Py_DECREF(type);
        goto fail;
      }
      Py_INCREF(dtype);
      Py_DECREF(type);
    }
    else
    {
      dtype = PyArray_DescrNew(npyarr->dec->dtype);
    }

    // If it's an object or string then fill a Python list and subsequently
    // convert. Otherwise we would need to somehow mess about with
    // reference counts when renewing memory.
    npyarr->elsize = dtype->elsize;
    if (PyDataType_REFCHK(dtype) || npyarr->elsize == 0)
    {
      Py_XDECREF(dtype);

      if (npyarr->dec->curdim > 1)
      {
        PyErr_SetString(PyExc_ValueError, "Cannot decode multidimensional arrays with variable length elements to numpy");
        goto fail;
      }
      npyarr->elcount = 0;
      npyarr->ret = PyList_New(0);
      if (!npyarr->ret)
      {
        goto fail;
      }
      ((JSONObjectDecoder*)npyarr->dec)->newArray = Object_npyNewArrayList;
      ((JSONObjectDecoder*)npyarr->dec)->arrayAddItem = Object_npyArrayListAddItem;
      ((JSONObjectDecoder*)npyarr->dec)->endArray = Object_npyEndArrayList;
      return Object_npyArrayListAddItem(prv, obj, value);
    }

    npyarr->ret = PyArray_NewFromDescr(&PyArray_Type, dtype, 1,
        &npyarr->elcount, NULL,NULL, 0, NULL);

    if (!npyarr->ret)
    {
      goto fail;
    }
  }

  if (i >= npyarr->elcount) {
    // Grow PyArray_DATA(ret):
    // this is similar for the strategy for PyListObject, but we use
    // 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ...
    if (npyarr->elsize == 0)
    {
      PyErr_SetString(PyExc_ValueError, "Cannot decode multidimensional arrays with variable length elements to numpy");
      goto fail;
    }

    npyarr->elcount = (i >> 1) + (i < 4 ? 4 : 2) + i;
    if (npyarr->elcount <= NPY_MAX_INTP/npyarr->elsize) {
      new_data = PyDataMem_RENEW(PyArray_DATA(npyarr->ret), npyarr->elcount * npyarr->elsize);
    }
    else {
      PyErr_NoMemory();
      goto fail;
    }
    ((PyArrayObject*) npyarr->ret)->data = (void*) new_data;

    // PyArray_BYTES(npyarr->ret) = new_data;
  }

  PyArray_DIMS(npyarr->ret)[0] = i + 1;

  if ((item = PyArray_GETPTR1(npyarr->ret, i)) == NULL
      || PyArray_SETITEM(npyarr->ret, item, value) == -1) {
    goto fail;
  }

  Py_DECREF( (PyObject *) value);
  npyarr->i++;
  return 1;

fail:

  Npy_releaseContext(npyarr);
  return 0;
}
Beispiel #4
0
/*
 * Conforms an output parameter 'out' to have 'ndim' dimensions
 * with dimensions of size one added in the appropriate places
 * indicated by 'axis_flags'.
 *
 * The return value is a view into 'out'.
 */
static PyArrayObject *
conform_reduce_result(int ndim, npy_bool *axis_flags,
                    PyArrayObject *out, int keepdims, const char *funcname)
{
    npy_intp strides[NPY_MAXDIMS], shape[NPY_MAXDIMS];
    npy_intp *strides_out = PyArray_STRIDES(out);
    npy_intp *shape_out = PyArray_DIMS(out);
    int idim, idim_out, ndim_out = PyArray_NDIM(out);
    PyArray_Descr *dtype;
    PyArrayObject_fields *ret;

    /*
     * If the 'keepdims' parameter is true, do a simpler validation and
     * return a new reference to 'out'.
     */
    if (keepdims) {
        if (PyArray_NDIM(out) != ndim) {
            PyErr_Format(PyExc_ValueError,
                    "output parameter for reduction operation %s "
                    "has the wrong number of dimensions (must match "
                    "the operand's when keepdims=True)", funcname);
            return NULL;
        }

        for (idim = 0; idim < ndim; ++idim) {
            if (axis_flags[idim]) {
                if (shape_out[idim] != 1) {
                    PyErr_Format(PyExc_ValueError,
                            "output parameter for reduction operation %s "
                            "has a reduction dimension not equal to one "
                            "(required when keepdims=True)", funcname);
                    return NULL;
                }
            }
        }

        Py_INCREF(out);
        return out;
    }

    /* Construct the strides and shape */
    idim_out = 0;
    for (idim = 0; idim < ndim; ++idim) {
        if (axis_flags[idim]) {
            strides[idim] = 0;
            shape[idim] = 1;
        }
        else {
            if (idim_out >= ndim_out) {
                PyErr_Format(PyExc_ValueError,
                        "output parameter for reduction operation %s "
                        "does not have enough dimensions", funcname);
                return NULL;
            }
            strides[idim] = strides_out[idim_out];
            shape[idim] = shape_out[idim_out];
            ++idim_out;
        }
    }

    if (idim_out != ndim_out) {
        PyErr_Format(PyExc_ValueError,
                "output parameter for reduction operation %s "
                "has too many dimensions", funcname);
        return NULL;
    }

    /* Allocate the view */
    dtype = PyArray_DESCR(out);
    Py_INCREF(dtype);
    ret = (PyArrayObject_fields *)PyArray_NewFromDescr(&PyArray_Type,
                               dtype,
                               ndim, shape,
                               strides,
                               PyArray_DATA(out),
                               PyArray_FLAGS(out),
                               NULL);
    if (ret == NULL) {
        return NULL;
    }
    Py_INCREF(out);
    if (PyArray_SetBaseObject((PyArrayObject *)ret, (PyObject *)out) < 0) {
        Py_DECREF(ret);
        return NULL;
    }

    return (PyArrayObject *)ret;
}
Beispiel #5
0
int c_function(int *n, float **mat)
{
  PyObject *pModule  = NULL;
  PyObject *pFunc = NULL;
  PyObject *pArg = NULL;
  PyObject *pRet = NULL;
  PyObject *pName = NULL;

  size_t size = *n;
  npy_intp *dim;
  int i, j;

  dim = (npy_intp *) malloc(sizeof(npy_intp)*(size));

  for (i=0; i < size; i++) dim[i] = size;

  Py_Initialize();

  if (!Py_IsInitialized())
  {
    fprintf(stderr, "nao foi possivel inicializar o python!\n");
    return -1;
  }

  init_numpy(); 

  PyObject* pMat = PyArray_NewFromDescr(
     &PyArray_Type, PyArray_DescrFromType(NPY_FLOAT), 
     2, dim, NULL, (void *) *mat, NPY_ARRAY_INOUT_FARRAY, NULL);

  Py_INCREF(pMat);

  pName = PyString_FromString("function");
  pModule = PyImport_Import(pName);

  pFunc = PyObject_GetAttrString(pModule, "py_function");

  if(!PyCallable_Check(pFunc))
  {
    printf("func not callable!\n");
    return -1;
  }

  pArg = PyTuple_New (2);
  PyTuple_SetItem(pArg, 0, (PyObject *) PyInt_FromLong(size));
  PyTuple_SetItem(pArg, 1, pMat);

  pRet = PyObject_CallObject(pFunc, pArg);

  printf("py ret: %s\n", PyString_AsString(pRet));

  Py_DECREF (pMat);
  Py_DECREF (pName);
  Py_DECREF (pModule);
  Py_DECREF (pFunc);
  Py_DECREF (pArg);
  Py_DECREF (pRet);

  Py_Finalize();

  return 0;
}
Beispiel #6
0
static
PyObject* NRT_adapt_ndarray_to_python(arystruct_t* arystruct, int ndim,
                                      int writeable, PyArray_Descr *descr) {
    PyArrayObject *array;
    MemInfoObject *miobj = NULL;
    PyObject *args;
    npy_intp *shape, *strides;
    int flags = 0;

    if (!PyArray_DescrCheck(descr)) {
        PyErr_Format(PyExc_TypeError,
                     "expected dtype object, got '%.200s'",
                     Py_TYPE(descr)->tp_name);
        return NULL;
    }

    if (arystruct->parent) {
        PyObject *obj = try_to_return_parent(arystruct, ndim, descr);
        if (obj)
            return obj;
    }

    if (arystruct->meminfo) {
        /* wrap into MemInfoObject */
        miobj = PyObject_New(MemInfoObject, &MemInfoType);
        args = PyTuple_New(1);
        /* SETITEM steals reference */
        PyTuple_SET_ITEM(args, 0, PyLong_FromVoidPtr(arystruct->meminfo));
        if (MemInfo_init(miobj, args, NULL)) {
            return NULL;
        }
        Py_DECREF(args);
    }

    shape = arystruct->shape_and_strides;
    strides = shape + ndim;
    Py_INCREF((PyObject *) descr);
    array = (PyArrayObject *) PyArray_NewFromDescr(&PyArray_Type, descr, ndim,
                                                   shape, strides, arystruct->data,
                                                   flags, (PyObject *) miobj);

    if (array == NULL)
        return NULL;

    /* Set writable */
#if NPY_API_VERSION >= 0x00000007
    if (writeable) {
        PyArray_ENABLEFLAGS(array, NPY_ARRAY_WRITEABLE);
    }
    else {
        PyArray_CLEARFLAGS(array, NPY_ARRAY_WRITEABLE);
    }
#else
    if (writeable) {
        array->flags |= NPY_WRITEABLE;
    }
    else {
        array->flags &= ~NPY_WRITEABLE;
    }
#endif

    if (miobj) {
        /* Set the MemInfoObject as the base object */
#if NPY_API_VERSION >= 0x00000007
        if (-1 == PyArray_SetBaseObject(array,
                                        (PyObject *) miobj))
        {
            Py_DECREF(array);
            Py_DECREF(miobj);
            return NULL;
        }
#else
        PyArray_BASE(array) = (PyObject *) miobj;
#endif

    }
    return (PyObject *) array;
}
PyObject * vl_siftdescriptor_python(
		PyArrayObject & in_grad,
		PyArrayObject & in_frames)
{
	// TODO: check types and dim
	//	"GRAD must be a 2xMxN matrix of class SINGLE."

	assert(in_grad.descr->type_num == PyArray_FLOAT);
	assert(in_frames.descr->type_num == PyArray_FLOAT64);
	assert(in_grad.flags & NPY_FORTRAN);
	assert(in_frames.flags & NPY_FORTRAN);

	int verbose = 0;
	int opt;

	//  TODO: check if we need to do a copy of the grad array
	float * grad_array;
	vl_sift_pix *grad;
	int M, N;

	double magnif = -1;
	double *ikeys = 0;
	int nikeys = 0;

	int i, j;


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

	// get frames nb and data pointer
	nikeys = in_frames.dimensions[1];
	ikeys = (double *) in_frames.data;


	// TODO: deal with optional params
	//  while ((opt = uNextOption(in, nin, options, &next, &optarg)) >= 0) {
	//    switch (opt) {
	//
	//      case opt_verbose :
	//        ++ verbose ;
	//        break ;
	//
	//      case opt_magnif :
	//        if (!uIsRealScalar(optarg) || (magnif = *mxGetPr(optarg)) < 0) {
	//          mexErrMsgTxt("MAGNIF must be a non-negative scalar.") ;
	//        }
	//        break ;
	//
	//      default :
	//        assert(0) ;
	//        break ;
	//    }
	//  }

	//  TODO: convert to Python
	//grad_array = mxDuplicateArray(in[IN_GRAD]); (copy?)
	grad = (float*) in_grad.data; //mxGetData(grad_array);
	M = in_grad.dimensions[1];
	N = in_grad.dimensions[2];


	/* transpose angles */
	for (i = 1; i < 2 * M * N; i += 2) {
		grad[i] = VL_PI / 2 - grad[i];
	}

	/* -----------------------------------------------------------------
	 *                                                            Do job
	 * -------------------------------------------------------------- */
	PyArrayObject * _descr;
	{
		VlSiftFilt *filt = 0;
		vl_uint8 *descr = 0;

		/* create a filter to process the image */
		filt = vl_sift_new(M, N, -1, -1, 0);

		if (magnif >= 0)
			vl_sift_set_magnif(filt, magnif);

		if (verbose) {
			printf("siftdescriptor: filter settings:\n");
			printf(
				"siftdescriptor:   magnif                = %g\n",
				vl_sift_get_magnif(filt));
			printf("siftdescriptor:   num of frames         = %d\n", nikeys);
		}

		{
			npy_intp dims[2];
			dims[0] = 128;
			dims[1] = nikeys;

			_descr = (PyArrayObject*) PyArray_NewFromDescr(
				&PyArray_Type, PyArray_DescrFromType(PyArray_UBYTE),
				2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL);

			descr = (vl_uint8*) _descr->data;
		}

		/* ...............................................................
		 *                                             Process each octave
		 * ............................................................ */
		for (i = 0; i < nikeys; ++i) {
			vl_sift_pix buf[128], rbuf[128];

			double y = *ikeys++;
			double x = *ikeys++;
			double s = *ikeys++;
			double th = VL_PI / 2 - *ikeys++;


			vl_sift_calc_raw_descriptor(filt, grad, buf, M, N, x, y, s, th);

			transpose_descriptor(rbuf, buf);

			for (j = 0; j < 128; ++j) {
				double x = 512.0 * rbuf[j];
				x = (x < 255.0) ? x : 255.0;
				*descr++ = (vl_uint8) (x);
			}
		}
		/* cleanup */
//		mxDestroyArray(grad_array);
		vl_sift_delete(filt);
	} /* job done */

	return PyArray_Return(_descr);
}
Beispiel #8
0
/** ------------------------------------------------------------------
 ** @brief Python entry point
 **/
PyObject * vl_dsift_python(
		PyArrayObject & pyArray,
		int opt_step,
		PyArrayObject & opt_bounds,
		int opt_size,
		bool opt_fast,
		bool opt_verbose,
		bool opt_norm)
{
	// check data type
	assert(pyArray.descr->type_num == PyArray_FLOAT);
	assert(pyArray.flags & NPY_FORTRAN);
	assert(opt_bounds.descr->type_num == PyArray_FLOAT);

	int verbose = 0;
	int opt;
	float const *data;
	int M, N;

	int step = 1;
	int size = 3;
	vl_bool norm = 0;

	vl_bool useFlatWindow = VL_FALSE;

	double *bounds = NULL;
	double boundBuffer[4];

	/* -----------------------------------------------------------------
	 *                                               Check the arguments
	 * -------------------------------------------------------------- */
	data = (float*) pyArray.data;
	M = pyArray.dimensions[0];
	N = pyArray.dimensions[1];

	if (opt_verbose)
		++verbose;
	if (opt_fast)
		useFlatWindow = 1;
	if (opt_norm)
		norm = 1;
	if (opt_bounds.nd == 1 && opt_bounds.dimensions[0] == 4) {
		double * tmp = (double *) opt_bounds.data;
		bounds = boundBuffer;
		for (int i = 0; i < 4; i++)
			bounds[i] = tmp[i];
	}
	if (opt_size >= 0)
		size = opt_size;
	if (opt_step >= 0)
		step = opt_step;


	// create PyTuple for outputs
	PyObject * tuple = PyTuple_New(2);

	/* -----------------------------------------------------------------
	 *                                                            Do job
	 * -------------------------------------------------------------- */
	{
		int numFrames;
		int descrSize;
		VlDsiftKeypoint const *frames;
		VlDsiftDescriptorGeometry const *geom;
		float const *descrs;
		int k, i;

		VlDsiftFilter *dsift;
		dsift = vl_dsift_new_basic(M, N, step, size);
		if (bounds) {
			vl_dsift_set_bounds(dsift, VL_MAX(bounds[0], 0), VL_MAX(
				bounds[1], 0), VL_MIN(bounds[2], M - 1), VL_MIN(bounds[3], N
					- 1));
		}
		vl_dsift_set_flat_window(dsift, useFlatWindow);

	    numFrames = vl_dsift_get_keypoint_num (dsift) ;
	    descrSize = vl_dsift_get_descriptor_size (dsift) ;
	    geom = vl_dsift_get_geometry(dsift);

		if (verbose) {
			int stepX;
			int stepY;
			int minX;
			int minY;
			int maxX;
			int maxY;
			vl_bool useFlatWindow;

			vl_dsift_get_steps(dsift, &stepX, &stepY);
			vl_dsift_get_bounds(dsift, &minX, &minY, &maxX, &maxY);
			useFlatWindow = vl_dsift_get_flat_window(dsift);

			printf("dsift: image size:        %d x %d\n", N, M);
			printf(
				"      bounds:            [%d, %d, %d, %d]\n", minY, minX,
				maxY, maxX);
			printf("      subsampling steps: %d, %d\n", stepY, stepX);
			printf(
				"      num bins:          [%d, %d, %d]\n", geom->numBinT,
				geom->numBinX, geom->numBinY);
			printf("      descriptor size:   %d\n", descrSize);
			printf(
				"      bin sizes:         [%d, %d]\n", geom->binSizeX,
				geom->binSizeY);
			printf("      flat window:       %s\n", VL_YESNO(useFlatWindow));
			printf("      number of frames:  %d\n", numFrames);
		}

		vl_dsift_process(dsift, data);

		frames = vl_dsift_get_keypoints(dsift);
		descrs = vl_dsift_get_descriptors(dsift);

		/* ---------------------------------------------------------------
		 *                                            Create output arrays
		 * ------------------------------------------------------------ */
		npy_intp dims[2];

		dims[0] = descrSize;
		dims[1] = numFrames;

		// allocate PyArray objects
		PyArrayObject * _descriptors = (PyArrayObject *) PyArray_NewFromDescr(
			&PyArray_Type, PyArray_DescrFromType(PyArray_UINT8),
			2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL);

		if (norm)
			dims[0] = 3;
		else
			dims[0] = 2;

		PyArrayObject * _frames = (PyArrayObject*) PyArray_NewFromDescr(
			&PyArray_Type, PyArray_DescrFromType(PyArray_DOUBLE),
			2, dims, NULL, NULL, NPY_F_CONTIGUOUS, NULL);

		// put PyArray objects in PyTuple
		PyTuple_SetItem(tuple, 0, PyArray_Return(_frames));
		PyTuple_SetItem(tuple, 1, PyArray_Return(_descriptors));

		/* ---------------------------------------------------------------
		 *                                                       Copy back
		 * ------------------------------------------------------------ */
		{
			float *tmpDescr = (float*) vl_malloc(sizeof(float) * descrSize);

			double *outFrameIter = (double*) _frames->data;
			vl_uint8 *outDescrIter = (vl_uint8 *) _descriptors->data;
			for (k = 0; k < numFrames; ++k) {
				*outFrameIter++ = frames[k].y;
				*outFrameIter++ = frames[k].x;

				/* We have an implied / 2 in the norm, because of the clipping
				 below */
				if (norm)
					*outFrameIter++ = frames[k].norm;

				vl_dsift_transpose_descriptor(
					tmpDescr, descrs + descrSize * k, geom->numBinT,
					geom->numBinX, geom->numBinY);

				for (i = 0; i < descrSize; ++i) {
					*outDescrIter++ = (vl_uint8) (VL_MIN(
						512.0F * tmpDescr[i], 255.0F));
				}
			}
			vl_free(tmpDescr);
		}
		vl_dsift_delete(dsift);
	}

	return tuple;
}
Beispiel #9
0
static PyObject *
array_slice(PyArrayObject *self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
    PyArrayObject *ret;
    PyArray_Descr *dtype;
    Py_ssize_t dim0;
    char *data;
    npy_intp shape[NPY_MAXDIMS];

    if (PyArray_NDIM(self) == 0) {
        PyErr_SetString(PyExc_ValueError, "cannot slice a 0-d array");
        return NULL;
    }

    dim0 = PyArray_DIM(self, 0);
    if (ilow < 0) {
        ilow = 0;
    }
    else if (ilow > dim0) {
        ilow = dim0;
    }
    if (ihigh < ilow) {
        ihigh = ilow;
    }
    else if (ihigh > dim0) {
        ihigh = dim0;
    }

    data = PyArray_DATA(self);
    if (ilow < ihigh) {
        data += ilow * PyArray_STRIDE(self, 0);
    }

    /* Same shape except dimension 0 */
    shape[0] = ihigh - ilow;
    memcpy(shape+1, PyArray_DIMS(self) + 1,
                        (PyArray_NDIM(self)-1)*sizeof(npy_intp));

    dtype = PyArray_DESCR(self);
    Py_INCREF(dtype);
    ret = (PyArrayObject *)PyArray_NewFromDescr(Py_TYPE(self), dtype,
                             PyArray_NDIM(self), shape,
                             PyArray_STRIDES(self), data,
             PyArray_FLAGS(self) & ~(NPY_ARRAY_MASKNA | NPY_ARRAY_OWNMASKNA),
                             (PyObject *)self);
    if (ret == NULL) {
        return NULL;
    }
    Py_INCREF(self);
    if (PyArray_SetBaseObject(ret, (PyObject *)self) < 0) {
        Py_DECREF(ret);
        return NULL;
    }
    PyArray_UpdateFlags(ret, NPY_ARRAY_UPDATE_ALL);

    /* Also take a view of the NA mask if it exists */
    if (PyArray_HASMASKNA(self)) {
        PyArrayObject_fields *fret = (PyArrayObject_fields *)ret;

        fret->maskna_dtype = PyArray_MASKNA_DTYPE(self);
        Py_INCREF(fret->maskna_dtype);

        data = PyArray_MASKNA_DATA(self);
        if (ilow < ihigh) {
            data += ilow * PyArray_MASKNA_STRIDES(self)[0];
        }
        fret->maskna_data = data;

        memcpy(fret->maskna_strides, PyArray_MASKNA_STRIDES(self),
                        PyArray_NDIM(self) * sizeof(npy_intp));

        /* This view doesn't own the mask */
        fret->flags |= NPY_ARRAY_MASKNA;
        fret->flags &= ~NPY_ARRAY_OWNMASKNA;
    }

    return (PyObject *)ret;
}