Merge pull request #27757 from vpisarev:matshape_inside_mat

Use MatShape instead of MatSize inside cv::Mat/cv::UMat #27757

**Merge together with https://github.com/opencv/opencv_contrib/pull/3996**
---

This PR continues cv::Mat/cv::UMat refactoring. See #26056, where `MatShape` was introduced. Now it's put inside cv::Mat/cv::UMat instead of a weird `MatSize`. MatSize is now an alias for MatShape:

**before:**

```
struct MatShape { ... };
struct MatSize { ... };

struct Mat {
    ...
    int dims;
    int rows;
    int cols;

    ...

    MatShape shape() const { ... /* constructs MatShape out of MatSize and returns it;
                                    layout is always 'unknown', because we don't store it */ }

    MatSize size; // size is not valid without the parent cv::Mat,
                  // because size.p may point to Mat::rows or to Mat::cols,
                  // depending on the dimensionality, and dims() returns Mat::dims.
    MatStep step; // may allocate memory, depending on the dimensionality.
    ...
};
```

**after:**

```
struct MatShape { ... };
typedef MatShape MatSize; // they are now synonyms

struct Mat {
    ...
    int dims;
    int rows;
    int cols;

    ...

    MatShape shape() const { return size; } // just return the embedded shape (including the proper layout information)

    MatSize size; // size is self-contained data structure that can be used without the parent cv::Mat.
                  // size.dims is now a copy of dims; size.p[*] contains copies of Mat::rows and Mat::cols when dims <= 2.
    MatStep step; // does not allocate extra memory buffers.
    ...
};
```

There are several reasons to do that:

1. the main reason is to be able to store data layout (MatShape::layout) inside each cv::Mat/cv::UMat. This is necessary for the proper shape inference in DNN module. In particular, it's necessary for the next step of DNN inference optimization where we introduce block-layout-optimized convolution and other operations. Later on, we can use layout information to support non-interleaved images (e.g. RRR...GGG...BBB...) or even batches of such images in core/imgproc modules.
2. the other reason is to represent 3D/4D/5D etc. tensors as cv::Mat/cv::UMat instances more conveniently, without extra dynamic memory allocation. Before this patch we allocated some memory buffers dynamically to store shape & steps for more than 2D arrays. Now the whole cv::Mat/cv::UMat header can be stored completely on stack/in a container. Creating another copy of Mat/UMat header is now done more efficiently.
3. the third reason is to introduce the new coding pattern: `dst.create(src.size, <dst_type>);`. The pattern is suitable for most of element-wise (including cloning) and filtering operations. This pattern does not only look crisp and self-documenting, it will also automatically copy shape (including layout) from the source tensor into the destination matrix/tensor.
4. in the future we might add `colorspace` member to MatShape that will allow to distinguish RGB from BGR or NV12. `dst.create(src.size, <dst_type>);` will then copy the colorspace information as well.

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [x] The feature is well documented and sample code can be built with the project CMake
This commit is contained in:
Vadim Pisarevsky
2025-09-15 15:03:34 +03:00
committed by GitHub
parent abcfb3c1e7
commit bdab54f79e
52 changed files with 521 additions and 624 deletions

View File

@@ -260,65 +260,66 @@ UMatDataAutoLock::~UMatDataAutoLock()
//////////////////////////////// UMat ////////////////////////////////
UMat::UMat(UMatUsageFlags _usageFlags) CV_NOEXCEPT
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{}
UMat::UMat(int _rows, int _cols, int _type, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_rows, _cols, _type);
}
UMat::UMat(int _rows, int _cols, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_rows, _cols, _type);
*this = _s;
}
UMat::UMat(Size _sz, int _type, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create( _sz.height, _sz.width, _type );
}
UMat::UMat(Size _sz, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_sz.height, _sz.width, _type);
*this = _s;
}
UMat::UMat(int _dims, const int* _sz, int _type, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_dims, _sz, _type);
}
UMat::UMat(int _dims, const int* _sz, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_dims, _sz, _type);
*this = _s;
}
UMat::UMat(const MatShape& _shape, int _type, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_shape.dims, _shape.p, _type);
}
UMat::UMat(const MatShape& _shape, int _type, const Scalar& _s, UMatUsageFlags _usageFlags)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(_usageFlags), u(0), offset(0)
{
create(_shape.dims, _shape.p, _type);
*this = _s;
}
UMat::UMat(const UMat& m)
: flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), allocator(m.allocator),
usageFlags(m.usageFlags), u(m.u), offset(m.offset), size(&rows)
usageFlags(m.usageFlags), u(m.u), offset(m.offset), size(m.size), step(m.step)
{
addref();
if( m.dims <= 2 )
{
int _1d = dims <= 1;
step.buf[0] = m.step.buf[0]; step.buf[1] = m.step.buf[1];
step.p = &step.buf[_1d];
size.p = &rows + _1d;
}
else
{
dims = 0;
copySize(m);
}
}
UMat& UMat::operator=(const UMat& m)
@@ -328,19 +329,11 @@ UMat& UMat::operator=(const UMat& m)
const_cast<UMat&>(m).addref();
release();
flags = m.flags;
if( dims <= 2 && m.dims <= 2 )
{
dims = m.dims;
rows = m.rows;
cols = m.cols;
int _1d = dims <= 1;
step.buf[0] = m.step.buf[0];
step.buf[1] = m.step.buf[1];
step.p = &step.buf[_1d];
size.p = &rows + _1d;
}
else
copySize(m);
dims = m.dims;
rows = m.rows;
cols = m.cols;
size = m.size;
step = m.step;
allocator = m.allocator;
usageFlags = m.usageFlags;
u = m.u;
@@ -392,9 +385,9 @@ void UMat::release()
{
if( u && CV_XADD(&(u->urefcount), -1) == 1 )
deallocate();
for(int i = 0; i < dims; i++)
size.p[i] = 0;
u = 0;
size.clear();
dims = cols = rows = 0;
}
bool UMat::empty() const
@@ -414,30 +407,19 @@ size_t UMat::total() const
MatShape UMat::shape() const
{
return dims == 0 && u == 0 ? MatShape() : MatShape(dims, size.p);
return size;
}
UMat::UMat(UMat&& m)
: flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), allocator(m.allocator),
usageFlags(m.usageFlags), u(m.u), offset(m.offset), size(&rows)
usageFlags(m.usageFlags), u(m.u), offset(m.offset)
{
if (m.dims <= 2) // move new step/size info
{
int _1d = m.dims <= 1;
step.buf[0] = m.step.buf[0];
step.buf[1] = m.step.buf[1];
step.p = &step.buf[_1d];
size.p = &rows + _1d;
}
else
{
CV_DbgAssert(m.step.p != m.step.buf && m.step.p != m.step.buf+1);
step.p = m.step.p;
size.p = m.size.p;
m.step.p = m.step.buf;
m.size.p = &m.rows;
}
m.flags = MAGIC_VAL; m.dims = m.rows = m.cols = 0;
size = m.size;
step = m.step;
m.flags = MAGIC_VAL;
m.usageFlags = USAGE_DEFAULT;
m.dims = m.rows = m.cols = 0;
m.size.clear();
m.allocator = NULL;
m.u = NULL;
m.offset = 0;
@@ -452,28 +434,8 @@ UMat& UMat::operator=(UMat&& m)
allocator = m.allocator; usageFlags = m.usageFlags;
u = m.u;
offset = m.offset;
if (step.p != step.buf && step.p != step.buf+1) // release self step/size
{
fastFree(step.p);
}
step.p = step.buf;
size.p = &rows;
if (m.dims <= 2) // move new step/size info
{
int _1d = dims <= 1;
step.buf[0] = m.step.buf[0];
step.buf[1] = m.step.buf[1];
step.p = &step.buf[_1d];
size.p = &rows + _1d;
}
else
{
CV_DbgAssert(m.step.p != m.step.buf && m.step.p != m.step.buf+1);
step.p = m.step.p;
size.p = m.size.p;
}
m.step.p = m.step.buf;
m.size.p = &m.rows;
size = m.size;
step = m.step;
m.flags = MAGIC_VAL;
m.usageFlags = USAGE_DEFAULT;
m.dims = m.rows = m.cols = 0;
@@ -503,80 +465,37 @@ void swap( UMat& a, UMat& b )
std::swap(a.u, b.u);
std::swap(a.offset, b.offset);
std::swap(a.size.p, b.size.p);
std::swap(a.step.p, b.step.p);
std::swap(a.step.buf[0], b.step.buf[0]);
std::swap(a.step.buf[1], b.step.buf[1]);
if(a.dims <= 2)
{
int a_1d = a.dims <= 1;
a.step.p = &a.step.buf[a_1d];
a.size.p = &a.rows + a_1d;
}
if( b.dims <= 2)
{
int b_1d = b.dims <= 1;
b.step.p = &b.step.buf[b_1d];
b.size.p = &b.rows + b_1d;
}
std::swap(a.size, b.size);
std::swap(a.step, b.step);
}
void setSize( UMat& m, int _dims, const int* _sz,
const size_t* _steps, bool autoSteps )
{
CV_Assert( 0 <= _dims && _dims <= CV_MAX_DIM );
if( m.dims != _dims )
{
if( m.step.p != m.step.buf && m.step.p != m.step.buf+1 )
{
fastFree(m.step.p);
}
m.step.p = m.step.buf;
m.size.p = &m.rows;
if( _dims > 2 )
{
m.step.p = (size_t*)fastMalloc(_dims*sizeof(m.step.p[0]) + (_dims+1)*sizeof(m.size.p[0]));
m.size.p = (int*)(m.step.p + _dims) + 1;
m.size.p[-1] = _dims;
m.rows = m.cols = -1;
}
}
CV_Assert( 0 <= _dims && _dims <= CV_MAX_DIM && _dims <= MatShape::MAX_DIMS);
m.dims = _dims;
size_t esz = CV_ELEM_SIZE(m.flags), total = esz;
if (_sz != 0) {
int i;
for( i = _dims-1; i >= 0; i-- )
{
int s = _sz[i];
CV_Assert( s >= 0 );
m.size.p[i] = s;
if( _steps )
m.step.p[i] = i < _dims-1 ? _steps[i] : esz;
else if( autoSteps )
{
m.step.p[i] = total;
int64 total1 = (int64)total*s;
if( (uint64)total1 != (size_t)total1 )
CV_Error( cv::Error::StsOutOfRange, "The total matrix size does not fit to \"size_t\" type" );
total = (size_t)total1;
}
m.size = MatShape(_dims, _sz);
m.step[std::max(_dims-1, 0)] = CV_ELEM_SIZE(m.flags);
for (int i = _dims-2; i >= 0; i--) {
size_t autostep = m.size[i+1]*m.step[i+1];
if (_steps) {
m.step[i] = _steps[i];
//CV_Assert(m.step[i] >= autostep);
} else if (autoSteps) {
m.step[i] = autostep;
} else {
m.step[i] = 0;
}
}
if( _dims < 2 )
if( _dims <= 2 )
{
m.cols = _dims >= 1 && _sz ? _sz[0] : 1;
m.rows = 1;
m.size.p = &m.cols;
m.step.buf[0] = m.cols*esz;
m.step.buf[1] = esz;
m.step.p = &m.step.buf[1];
m.cols = _dims == 0 ? 1 : _sz ? _sz[_dims > 1] : 0;
m.rows = _dims < 2 ? 1 : _sz ? _sz[0] : 0;
} else {
m.cols = m.rows = -1;
}
}
@@ -622,11 +541,12 @@ UMat Mat::getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags) const
accessFlags |= ACCESS_RW;
UMatData* new_u = NULL;
MatStep new_step = step;
{
MatAllocator *a = allocator, *a0 = getDefaultAllocator();
if(!a)
a = a0;
new_u = a->allocate(dims, size.p, type(), data, step.p, accessFlags, usageFlags);
new_u = a->allocate(dims, size.p, type(), data, new_step.p, accessFlags, usageFlags);
new_u->originalUMatData = u;
}
bool allocated = false;
@@ -658,7 +578,7 @@ UMat Mat::getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags) const
{
hdr.flags = flags;
hdr.usageFlags = usageFlags;
setSize(hdr, dims, size.p, step.p);
setSize(hdr, dims, size.p, new_step.p);
finalizeHdr(hdr);
hdr.u = new_u;
hdr.offset = 0; //data - datastart;
@@ -733,13 +653,13 @@ void UMat::create(int d0, const int* _sizes, int _type, UMatUsageFlags _usageFla
}
try
{
u = a->allocate(dims, size, _type, 0, step.p, ACCESS_RW /* ignored */, usageFlags);
u = a->allocate(dims, size.p, _type, 0, step.p, ACCESS_RW /* ignored */, usageFlags);
CV_Assert(u != 0);
}
catch(...)
{
if(a != a0)
u = a0->allocate(dims, size, _type, 0, step.p, ACCESS_RW /* ignored */, usageFlags);
u = a0->allocate(dims, size.p, _type, 0, step.p, ACCESS_RW /* ignored */, usageFlags);
CV_Assert(u != 0);
}
CV_Assert( step[dims-1] == (size_t)CV_ELEM_SIZE(flags) );
@@ -747,7 +667,7 @@ void UMat::create(int d0, const int* _sizes, int _type, UMatUsageFlags _usageFla
finalizeHdr(*this);
addref();
dims = d0;
size.dims = dims = d0;
}
void UMat::create(const std::vector<int>& _sizes, int _type, UMatUsageFlags _usageFlags)
@@ -818,20 +738,16 @@ void UMat::fitSameSize(InputArray m, int _type, UMatUsageFlags _usageFlags)
void UMat::copySize(const UMat& m)
{
setSize(*this, m.dims, 0, 0);
for( int i = 0; i < dims; i++ )
{
size[i] = m.size[i];
step[i] = m.step[i];
}
dims = m.dims;
cols = m.cols;
rows = m.rows;
size = m.size;
step = m.step;
}
UMat::~UMat()
{
release();
if( step.p != step.buf && step.p != step.buf+1 )
fastFree(step.p);
}
void UMat::deallocate()
@@ -843,33 +759,37 @@ void UMat::deallocate()
UMat::UMat(const UMat& m, const Range& _rowRange, const Range& _colRange)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0)
{
CV_Assert( m.dims >= 2 );
CV_Assert( m.dims >= 2 && m.dims <= MatShape::MAX_DIMS );
if( m.dims > 2 )
{
AutoBuffer<Range> rs(m.dims);
Range rs[MatShape::MAX_DIMS];
rs[0] = _rowRange;
rs[1] = _colRange;
for( int i = 2; i < m.dims; i++ )
rs[i] = Range::all();
*this = m(rs.data());
*this = m(rs);
return;
}
*this = m;
if( _rowRange != Range::all() && _rowRange != Range(0,rows) )
{
CV_Assert( 0 <= _rowRange.start && _rowRange.start <= _rowRange.end && _rowRange.end <= m.rows );
rows = _rowRange.size();
CV_Assert( 0 <= _rowRange.start &&
_rowRange.start <= _rowRange.end &&
_rowRange.end <= m.rows );
size[0] = rows = _rowRange.size();
offset += step*_rowRange.start;
flags |= SUBMATRIX_FLAG;
}
if( _colRange != Range::all() && _colRange != Range(0,cols) )
{
CV_Assert( 0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols );
cols = _colRange.size();
CV_Assert( 0 <= _colRange.start &&
_colRange.start <= _colRange.end &&
_colRange.end <= m.cols );
size[1] = cols = _colRange.size();
offset += _colRange.start*elemSize();
flags |= SUBMATRIX_FLAG;
}
@@ -886,7 +806,8 @@ UMat::UMat(const UMat& m, const Range& _rowRange, const Range& _colRange)
UMat::UMat(const UMat& m, const Rect& roi)
: flags(m.flags), dims(2), rows(roi.height), cols(roi.width),
allocator(m.allocator), usageFlags(m.usageFlags), u(m.u), offset(m.offset + roi.y*m.step[0]), size(&rows)
allocator(m.allocator), usageFlags(m.usageFlags), u(m.u),
offset(m.offset + roi.y*m.step[0]), size(2)
{
CV_Assert( m.dims <= 2 );
@@ -897,7 +818,11 @@ UMat::UMat(const UMat& m, const Rect& roi)
if( roi.width < m.cols || roi.height < m.rows )
flags |= SUBMATRIX_FLAG;
step[0] = m.step[0]; step[1] = esz;
size[0] = rows;
size[1] = cols;
step[0] = m.dims == 2 ? m.step[0] : cols*esz;
step[1] = esz;
updateContinuityFlag();
addref();
@@ -910,7 +835,7 @@ UMat::UMat(const UMat& m, const Rect& roi)
UMat::UMat(const UMat& m, const Range* ranges)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0)
{
int i, d = m.dims;
@@ -931,11 +856,16 @@ UMat::UMat(const UMat& m, const Range* ranges)
flags |= SUBMATRIX_FLAG;
}
}
if (d <= 2) {
rows = d == 2 ? size[0] : 1;
cols = d <= 0 ? (d >= 0) : size[d > 1];
}
updateContinuityFlag();
}
UMat::UMat(const UMat& m, const std::vector<Range>& ranges)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows)
: flags(MAGIC_VAL), dims(0), rows(0), cols(0), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0)
{
int i, d = m.dims;
@@ -956,6 +886,11 @@ UMat::UMat(const UMat& m, const std::vector<Range>& ranges)
flags |= SUBMATRIX_FLAG;
}
}
if (d <= 2) {
rows = d == 2 ? size[0] : 1;
cols = d <= 0 ? (d >= 0) : size[d > 1];
}
updateContinuityFlag();
}
@@ -1069,8 +1004,12 @@ UMat UMat::reshape(int new_cn, int new_rows) const
CV_Error( cv::Error::StsBadArg, "The total number of matrix elements "
"is not divisible by the new number of rows" );
hdr.rows = new_rows;
hdr.step.buf[0] = total_width * elemSize1();
hdr.size[0] = hdr.rows = new_rows;
hdr.step[0] = total_width * elemSize1();
} else {
hdr.size[0] = hdr.rows = rows;
if (dims <= 1)
hdr.step[0] = cols * CV_ELEM_SIZE(flags);
}
int new_width = total_width / new_cn;
@@ -1079,12 +1018,10 @@ UMat UMat::reshape(int new_cn, int new_rows) const
CV_Error( cv::Error::BadNumChannels,
"The total width is not divisible by the new number of channels" );
hdr.dims = 2;
hdr.cols = new_width;
hdr.size.dims = hdr.dims = 2;
hdr.size[1] = hdr.cols = new_width;
hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((new_cn-1) << CV_CN_SHIFT);
hdr.step.buf[1] = CV_ELEM_SIZE(hdr.flags);
hdr.step.p = &hdr.step.buf[0];
hdr.size.p = &hdr.rows;
hdr.step[1] = CV_ELEM_SIZE(hdr.flags);
return hdr;
}
@@ -1328,7 +1265,7 @@ void UMat::copyTo(OutputArray _dst, InputArray _mask) const
if (ocl::useOpenCL() && _dst.isUMat() && dims <= 2)
{
UMatData * prevu = _dst.getUMat().u;
_dst.create( dims, size, type() );
_dst.create( size, type() );
UMat dst = _dst.getUMat();
@@ -1453,6 +1390,11 @@ UMat UMat::zeros(int ndims, const int* sz, int type, UMatUsageFlags usageFlags)
return UMat(ndims, sz, type, Scalar::all(0), usageFlags);
}
UMat UMat::zeros(const MatShape& shape, int type, UMatUsageFlags usageFlags)
{
return UMat(shape.dims, shape.p, type, Scalar::all(0), usageFlags);
}
UMat UMat::ones(int rows, int cols, int type, UMatUsageFlags usageFlags)
{
return UMat(rows, cols, type, Scalar(1), usageFlags);
@@ -1468,6 +1410,11 @@ UMat UMat::ones(int ndims, const int* sz, int type, UMatUsageFlags usageFlags)
return UMat(ndims, sz, type, Scalar(1), usageFlags);
}
UMat UMat::ones(const MatShape& shape, int type, UMatUsageFlags usageFlags)
{
return UMat(shape.dims, shape.p, type, Scalar(1), usageFlags);
}
}
/* End of file. */