Ask Your Question

copying a portion of a matrix to itself

asked 2012-08-03 21:19:57 -0600

darKoram gravatar image

updated 2012-08-03 21:23:21 -0600

Hi, I'm working on an application that does some DSP for streaming data. OpenCV Mat seems like a pretty elegant solution for implementing a circular buffer inside a parent array. The moving window array will increment forward with each new dataRecord input as a column. When the front of the window (leading direction of motion) reaches the end of the parent matrix, I need to deep copy the window data to the start of the parent matrix. copyTo() looks good:

The method copies the matrix data to another matrix. Before copying the data, the method invokes

m.create(this->size(), this->type);

so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices.

I'd like to use copyTo

public void wrapWindowToStart() {
            //... extra code

but based on the comments above i'm not sure if that will work. Does create() decide reallocation isn't needed and everything just works fine? For now, I'm doing something like this:

for (int i=mWindowBack; i<mWindowFront; i++) {
    for (int j=0; j<mRecordLength;j++) {
        mGpuDataBuffer.put(i-mQueueLength+mWindowLength, j, mGpuDataBuffer.get(i, j))
edit retag flag offensive close merge delete


"JNI calls are really expensive and should be minimzed" so that's extra incentive to find a call from the native library that works for my case.

Looking at the source code for Mat::copyTo in copy.cpp and Mat::create in matrix.cpp it appears that create() only allocates memory if the dimensions or type don't match. So trying to call M.copyTo(submatrixOfM) would cause a problem because create() would see dimension mismatch and try to allocate data within an already alocated space, or allocate the new data outside of the parent matrix (not sure which).

darKoram gravatar imagedarKoram ( 2012-08-04 15:00:09 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2012-08-04 17:02:49 -0600

darKoram gravatar image

It should be possible to create two submatrices within the parent matrix. submatrix Window0 could stay fixed at the start of the Parent matrix. Window1 could me the moving window. When Window1 bumps into the end of the Parent matrix, copy its contents into window0.


This should do the trick, since the dimensions and type match, create() should just copy headers.

edit flag offensive delete link more

Question Tools

1 follower


Asked: 2012-08-03 21:19:57 -0600

Seen: 866 times

Last updated: Aug 04 '12