matrix.cpp 36.0 KB
Newer Older
1 2 3
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
4 5

#include "precomp.hpp"
A
Alexander Alekhin 已提交
6 7
#include "bufferpool.impl.hpp"

8 9
namespace cv {

10
void MatAllocator::map(UMatData*, AccessFlag) const
11 12
{
}
13

14 15 16
void MatAllocator::unmap(UMatData* u) const
{
    if(u->urefcount == 0 && u->refcount == 0)
A
Alexander Alekhin 已提交
17
    {
18
        deallocate(u);
A
Alexander Alekhin 已提交
19
    }
20
}
21

22 23 24 25 26 27 28 29 30 31
void MatAllocator::download(UMatData* u, void* dstptr,
         int dims, const size_t sz[],
         const size_t srcofs[], const size_t srcstep[],
         const size_t dststep[]) const
{
    if(!u)
        return;
    int isz[CV_MAX_DIM];
    uchar* srcptr = u->data;
    for( int i = 0; i < dims; i++ )
32
    {
33 34
        CV_Assert( sz[i] <= (size_t)INT_MAX );
        if( sz[i] == 0 )
35
            return;
36
        if( srcofs )
37
            srcptr += srcofs[i]*(i <= dims-2 ? srcstep[i] : 1);
38
        isz[i] = (int)sz[i];
39 40
    }

41 42
    Mat src(dims, isz, CV_8U, srcptr, srcstep);
    Mat dst(dims, isz, CV_8U, dstptr, dststep);
43

44 45 46
    const Mat* arrays[] = { &src, &dst };
    uchar* ptrs[2];
    NAryMatIterator it(arrays, ptrs, 2);
47
    size_t planesz = it.size;
48

49
    for( size_t j = 0; j < it.nplanes; j++, ++it )
50 51 52 53 54 55 56 57 58 59 60 61 62
        memcpy(ptrs[1], ptrs[0], planesz);
}


void MatAllocator::upload(UMatData* u, const void* srcptr, int dims, const size_t sz[],
                    const size_t dstofs[], const size_t dststep[],
                    const size_t srcstep[]) const
{
    if(!u)
        return;
    int isz[CV_MAX_DIM];
    uchar* dstptr = u->data;
    for( int i = 0; i < dims; i++ )
63
    {
64 65
        CV_Assert( sz[i] <= (size_t)INT_MAX );
        if( sz[i] == 0 )
66
            return;
67
        if( dstofs )
68
            dstptr += dstofs[i]*(i <= dims-2 ? dststep[i] : 1);
69
        isz[i] = (int)sz[i];
70 71
    }

72 73 74 75 76 77
    Mat src(dims, isz, CV_8U, (void*)srcptr, srcstep);
    Mat dst(dims, isz, CV_8U, dstptr, dststep);

    const Mat* arrays[] = { &src, &dst };
    uchar* ptrs[2];
    NAryMatIterator it(arrays, ptrs, 2);
78
    size_t planesz = it.size;
79

80
    for( size_t j = 0; j < it.nplanes; j++, ++it )
81 82 83 84
        memcpy(ptrs[1], ptrs[0], planesz);
}

void MatAllocator::copy(UMatData* usrc, UMatData* udst, int dims, const size_t sz[],
85
                  const size_t srcofs[], const size_t srcstep[],
86
                  const size_t dstofs[], const size_t dststep[], bool /*sync*/) const
87
{
88
    CV_INSTRUMENT_REGION();
89

90 91 92 93 94 95
    if(!usrc || !udst)
        return;
    int isz[CV_MAX_DIM];
    uchar* srcptr = usrc->data;
    uchar* dstptr = udst->data;
    for( int i = 0; i < dims; i++ )
96
    {
97 98
        CV_Assert( sz[i] <= (size_t)INT_MAX );
        if( sz[i] == 0 )
I
Ilya Lavrenov 已提交
99
            return;
100
        if( srcofs )
I
Ilya Lavrenov 已提交
101
            srcptr += srcofs[i]*(i <= dims-2 ? srcstep[i] : 1);
102
        if( dstofs )
I
Ilya Lavrenov 已提交
103
            dstptr += dstofs[i]*(i <= dims-2 ? dststep[i] : 1);
104 105
        isz[i] = (int)sz[i];
    }
106

107 108
    Mat src(dims, isz, CV_8U, srcptr, srcstep);
    Mat dst(dims, isz, CV_8U, dstptr, dststep);
109

110 111 112
    const Mat* arrays[] = { &src, &dst };
    uchar* ptrs[2];
    NAryMatIterator it(arrays, ptrs, 2);
113
    size_t planesz = it.size;
114

115
    for( size_t j = 0; j < it.nplanes; j++, ++it )
116 117
        memcpy(ptrs[1], ptrs[0], planesz);
}
118

A
Alexander Alekhin 已提交
119
BufferPoolController* MatAllocator::getBufferPoolController(const char* id) const
A
Alexander Alekhin 已提交
120
{
H
Hamdi Sahloul 已提交
121
    CV_UNUSED(id);
A
Alexander Alekhin 已提交
122 123 124 125
    static DummyBufferPoolController dummy;
    return &dummy;
}

126
class StdMatAllocator CV_FINAL : public MatAllocator
127 128 129
{
public:
    UMatData* allocate(int dims, const int* sizes, int type,
130
                       void* data0, size_t* step, AccessFlag /*flags*/, UMatUsageFlags /*usageFlags*/) const CV_OVERRIDE
131
    {
132 133
        size_t total = CV_ELEM_SIZE(type);
        for( int i = dims-1; i >= 0; i-- )
134
        {
135 136 137 138 139 140 141 142 143 144 145
            if( step )
            {
                if( data0 && step[i] != CV_AUTOSTEP )
                {
                    CV_Assert(total <= step[i]);
                    total = step[i];
                }
                else
                    step[i] = total;
            }
            total *= sizes[i];
146
        }
147 148 149 150 151 152
        uchar* data = data0 ? (uchar*)data0 : (uchar*)fastMalloc(total);
        UMatData* u = new UMatData(this);
        u->data = u->origdata = data;
        u->size = total;
        if(data0)
            u->flags |= UMatData::USER_ALLOCATED;
153

154 155
        return u;
    }
156

157
    bool allocate(UMatData* u, AccessFlag /*accessFlags*/, UMatUsageFlags /*usageFlags*/) const CV_OVERRIDE
158 159 160
    {
        if(!u) return false;
        return true;
161 162
    }

163
    void deallocate(UMatData* u) const CV_OVERRIDE
164
    {
165 166 167
        if(!u)
            return;

168 169 170
        CV_Assert(u->urefcount == 0);
        CV_Assert(u->refcount == 0);
        if( !(u->flags & UMatData::USER_ALLOCATED) )
171
        {
172 173
            fastFree(u->origdata);
            u->origdata = 0;
174
        }
175
        delete u;
176 177
    }
};
178

179 180
namespace
{
M
Matthias Grundmann 已提交
181
    MatAllocator* volatile g_matAllocator = NULL;
182
}
183

184 185
MatAllocator* Mat::getDefaultAllocator()
{
D
Dan 已提交
186 187
    if (g_matAllocator == NULL)
    {
M
Matthias Grundmann 已提交
188 189 190 191 192
        cv::AutoLock lock(cv::getInitializationMutex());
        if (g_matAllocator == NULL)
        {
            g_matAllocator = getStdAllocator();
        }
D
Dan 已提交
193 194
    }
    return g_matAllocator;
195 196 197
}
void Mat::setDefaultAllocator(MatAllocator* allocator)
{
D
Dan 已提交
198
    g_matAllocator = allocator;
199
}
200 201
MatAllocator* Mat::getStdAllocator()
{
D
Dan 已提交
202
    CV_SINGLETON_LAZY_INIT(MatAllocator, new StdMatAllocator())
203 204
}

205
//==================================================================================================
V
Vadim Pisarevsky 已提交
206

207
bool MatSize::operator==(const MatSize& sz) const CV_NOEXCEPT
208 209 210 211 212 213 214 215 216 217 218 219 220 221
{
    int d = dims();
    int dsz = sz.dims();
    if( d != dsz )
        return false;
    if( d == 2 )
        return p[0] == sz.p[0] && p[1] == sz.p[1];

    for( int i = 0; i < d; i++ )
        if( p[i] != sz.p[i] )
            return false;
    return true;
}

222
void setSize( Mat& m, int _dims, const int* _sz, const size_t* _steps, bool autoSteps)
V
Vadim Pisarevsky 已提交
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
{
    CV_Assert( 0 <= _dims && _dims <= CV_MAX_DIM );
    if( m.dims != _dims )
    {
        if( m.step.p != m.step.buf )
        {
            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;
238
            m.rows = m.cols = -1;
V
Vadim Pisarevsky 已提交
239 240
        }
    }
241

V
Vadim Pisarevsky 已提交
242 243 244
    m.dims = _dims;
    if( !_sz )
        return;
245

I
Ilya Lavrenov 已提交
246
    size_t esz = CV_ELEM_SIZE(m.flags), esz1 = CV_ELEM_SIZE1(m.flags), total = esz;
247
    for( int i = _dims-1; i >= 0; i-- )
V
Vadim Pisarevsky 已提交
248 249
    {
        int s = _sz[i];
250
        CV_Assert( s >= 0 );
V
Vadim Pisarevsky 已提交
251
        m.size.p[i] = s;
252

V
Vadim Pisarevsky 已提交
253
        if( _steps )
I
Ilya Lavrenov 已提交
254
        {
255
            if (i < _dims-1)
I
Ilya Lavrenov 已提交
256
            {
257 258 259 260
                if (_steps[i] % esz1 != 0)
                {
                    CV_Error_(Error::BadStep, ("Step %zu for dimension %d must be a multiple of esz1 %zu", _steps[i], i, esz1));
                }
I
Ilya Lavrenov 已提交
261

262 263 264 265 266 267
                m.step.p[i] = _steps[i];
            }
            else
            {
                m.step.p[i] = esz;
            }
I
Ilya Lavrenov 已提交
268
        }
V
Vadim Pisarevsky 已提交
269 270 271
        else if( autoSteps )
        {
            m.step.p[i] = total;
V
Vincent Rabaud 已提交
272
            uint64 total1 = (uint64)total*s;
V
Vadim Pisarevsky 已提交
273 274 275 276 277
            if( (uint64)total1 != (size_t)total1 )
                CV_Error( CV_StsOutOfRange, "The total matrix size does not fit to \"size_t\" type" );
            total = (size_t)total1;
        }
    }
278

V
Vadim Pisarevsky 已提交
279 280 281 282 283 284 285
    if( _dims == 1 )
    {
        m.dims = 2;
        m.cols = 1;
        m.step[1] = esz;
    }
}
286

287
int updateContinuityFlag(int flags, int dims, const int* size, const size_t* step)
V
Vadim Pisarevsky 已提交
288 289
{
    int i, j;
290
    for( i = 0; i < dims; i++ )
V
Vadim Pisarevsky 已提交
291
    {
292
        if( size[i] > 1 )
V
Vadim Pisarevsky 已提交
293 294
            break;
    }
295

296 297
    uint64 t = (uint64)size[std::min(i, dims-1)]*CV_MAT_CN(flags);
    for( j = dims-1; j > i; j-- )
V
Vadim Pisarevsky 已提交
298
    {
299 300
        t *= size[j];
        if( step[j]*size[j] < step[j-1] )
V
Vadim Pisarevsky 已提交
301 302
            break;
    }
303

304 305 306 307 308 309 310 311
    if( j <= i && t == (uint64)(int)t )
        return flags | Mat::CONTINUOUS_FLAG;
    return flags & ~Mat::CONTINUOUS_FLAG;
}

void Mat::updateContinuityFlag()
{
    flags = cv::updateContinuityFlag(flags, dims, size.p, step.p);
312
}
313

314
void finalizeHdr(Mat& m)
315
{
316
    m.updateContinuityFlag();
317 318
    int d = m.dims;
    if( d > 2 )
V
Vadim Pisarevsky 已提交
319
        m.rows = m.cols = -1;
320
    if(m.u)
321
        m.datastart = m.data = m.u->data;
V
Vadim Pisarevsky 已提交
322 323
    if( m.data )
    {
324 325 326
        m.datalimit = m.datastart + m.size[0]*m.step[0];
        if( m.size[0] > 0 )
        {
327
            m.dataend = m.ptr() + m.size[d-1]*m.step[d-1];
328
            for( int i = 0; i < d-1; i++ )
329 330 331 332
                m.dataend += (m.size[i] - 1)*m.step[i];
        }
        else
            m.dataend = m.datalimit;
V
Vadim Pisarevsky 已提交
333
    }
334 335
    else
        m.dataend = m.datalimit = 0;
V
Vadim Pisarevsky 已提交
336
}
337

338 339
//======================================= Mat ======================================================

340
Mat::Mat() CV_NOEXCEPT
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{}

Mat::Mat(int _rows, int _cols, int _type)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_rows, _cols, _type);
}

Mat::Mat(int _rows, int _cols, int _type, const Scalar& _s)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_rows, _cols, _type);
    *this = _s;
}

Mat::Mat(Size _sz, int _type)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create( _sz.height, _sz.width, _type );
}

Mat::Mat(Size _sz, int _type, const Scalar& _s)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_sz.height, _sz.width, _type);
    *this = _s;
}

Mat::Mat(int _dims, const int* _sz, int _type)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_dims, _sz, _type);
}

Mat::Mat(int _dims, const int* _sz, int _type, const Scalar& _s)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_dims, _sz, _type);
    *this = _s;
}

Mat::Mat(const std::vector<int>& _sz, int _type)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_sz, _type);
}

Mat::Mat(const std::vector<int>& _sz, int _type, const Scalar& _s)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows), step(0)
{
    create(_sz, _type);
    *this = _s;
}

Mat::Mat(const Mat& m)
    : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data),
      datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator),
      u(m.u), size(&rows), step(0)
{
    if( u )
        CV_XADD(&u->refcount, 1);
    if( m.dims <= 2 )
    {
        step[0] = m.step[0]; step[1] = m.step[1];
    }
    else
    {
        dims = 0;
        copySize(m);
    }
}

Mat::Mat(int _rows, int _cols, int _type, void* _data, size_t _step)
    : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_rows), cols(_cols),
      data((uchar*)_data), datastart((uchar*)_data), dataend(0), datalimit(0),
      allocator(0), u(0), size(&rows)
{
    CV_Assert(total() == 0 || data != NULL);

    size_t esz = CV_ELEM_SIZE(_type), esz1 = CV_ELEM_SIZE1(_type);
    size_t minstep = cols * esz;
    if( _step == AUTO_STEP )
    {
        _step = minstep;
    }
    else
    {
        CV_Assert( _step >= minstep );
        if (_step % esz1 != 0)
        {
            CV_Error(Error::BadStep, "Step must be a multiple of esz1");
        }
    }
    step[0] = _step;
    step[1] = esz;
    datalimit = datastart + _step * rows;
    dataend = datalimit - _step + minstep;
    updateContinuityFlag();
}

Mat::Mat(Size _sz, int _type, void* _data, size_t _step)
    : flags(MAGIC_VAL + (_type & TYPE_MASK)), dims(2), rows(_sz.height), cols(_sz.width),
      data((uchar*)_data), datastart((uchar*)_data), dataend(0), datalimit(0),
      allocator(0), u(0), size(&rows)
{
    CV_Assert(total() == 0 || data != NULL);

    size_t esz = CV_ELEM_SIZE(_type), esz1 = CV_ELEM_SIZE1(_type);
    size_t minstep = cols*esz;
    if( _step == AUTO_STEP )
    {
        _step = minstep;
    }
    else
    {
466
        CV_CheckGE(_step, minstep, "");
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

        if (_step % esz1 != 0)
        {
            CV_Error(Error::BadStep, "Step must be a multiple of esz1");
        }
    }
    step[0] = _step;
    step[1] = esz;
    datalimit = datastart + _step*rows;
    dataend = datalimit - _step + minstep;
    updateContinuityFlag();
}


Mat::~Mat()
{
    release();
    if( step.p != step.buf )
        fastFree(step.p);
}

Mat& Mat::operator=(const Mat& m)
{
    if( this != &m )
    {
        if( m.u )
            CV_XADD(&m.u->refcount, 1);
        release();
        flags = m.flags;
        if( dims <= 2 && m.dims <= 2 )
        {
            dims = m.dims;
            rows = m.rows;
            cols = m.cols;
            step[0] = m.step[0];
            step[1] = m.step[1];
        }
        else
            copySize(m);
        data = m.data;
        datastart = m.datastart;
        dataend = m.dataend;
        datalimit = m.datalimit;
        allocator = m.allocator;
        u = m.u;
    }
    return *this;
}

Mat Mat::clone() const
{
    Mat m;
    copyTo(m);
    return m;
}

void Mat::assignTo( Mat& m, int _type ) const
{
    if( _type < 0 )
        m = *this;
    else
        convertTo(m, _type);
}

void Mat::create(int _rows, int _cols, int _type)
{
    _type &= TYPE_MASK;
    if( dims <= 2 && rows == _rows && cols == _cols && type() == _type && data )
        return;
    int sz[] = {_rows, _cols};
    create(2, sz, _type);
}

void Mat::create(Size _sz, int _type)
{
    create(_sz.height, _sz.width, _type);
}

void Mat::addref()
{
    if( u )
        CV_XADD(&u->refcount, 1);
}

void Mat::release()
{
    if( u && CV_XADD(&u->refcount, -1) == 1 )
        deallocate();
    u = NULL;
    datastart = dataend = datalimit = data = 0;
    for(int i = 0; i < dims; i++)
        size.p[i] = 0;
#ifdef _DEBUG
    flags = MAGIC_VAL;
    dims = rows = cols = 0;
    if(step.p != step.buf)
    {
        fastFree(step.p);
        step.p = step.buf;
        size.p = &rows;
    }
#endif
}

size_t Mat::step1(int i) const
{
    return step.p[i] / elemSize1();
}

bool Mat::empty() const
{
    return data == 0 || total() == 0 || dims == 0;
}

size_t Mat::total() const
{
    if( dims <= 2 )
        return (size_t)rows * cols;
    size_t p = 1;
    for( int i = 0; i < dims; i++ )
        p *= size[i];
    return p;
}

size_t Mat::total(int startDim, int endDim) const
{
    CV_Assert( 0 <= startDim && startDim <= endDim);
    size_t p = 1;
    int endDim_ = endDim <= dims ? endDim : dims;
    for( int i = startDim; i < endDim_; i++ )
        p *= size[i];
    return p;
}


602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
Mat::Mat(Mat&& m)
    : flags(m.flags), dims(m.dims), rows(m.rows), cols(m.cols), data(m.data),
      datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit), allocator(m.allocator),
      u(m.u), size(&rows)
{
    if (m.dims <= 2)  // move new step/size info
    {
        step[0] = m.step[0];
        step[1] = m.step[1];
    }
    else
    {
        CV_Assert(m.step.p != m.step.buf);
        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;
    m.data = NULL; m.datastart = NULL; m.dataend = NULL; m.datalimit = NULL;
    m.allocator = NULL;
    m.u = NULL;
}


Mat& Mat::operator=(Mat&& m)
{
    if (this == &m)
      return *this;

    release();
    flags = m.flags; dims = m.dims; rows = m.rows; cols = m.cols; data = m.data;
    datastart = m.datastart; dataend = m.dataend; datalimit = m.datalimit; allocator = m.allocator;
    u = m.u;
    if (step.p != step.buf) // release self step/size
    {
        fastFree(step.p);
        step.p = step.buf;
        size.p = &rows;
    }
    if (m.dims <= 2) // move new step/size info
    {
        step[0] = m.step[0];
        step[1] = m.step[1];
    }
    else
    {
        CV_Assert(m.step.p != m.step.buf);
        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;
    m.data = NULL; m.datastart = NULL; m.dataend = NULL; m.datalimit = NULL;
    m.allocator = NULL;
    m.u = NULL;
    return *this;
}

662

V
Vadim Pisarevsky 已提交
663 664 665
void Mat::create(int d, const int* _sizes, int _type)
{
    int i;
V
Vladislav Vinogradov 已提交
666
    CV_Assert(0 <= d && d <= CV_MAX_DIM && _sizes);
V
Vadim Pisarevsky 已提交
667
    _type = CV_MAT_TYPE(_type);
668

V
Vadim Pisarevsky 已提交
669 670 671 672 673 674 675 676 677 678
    if( data && (d == dims || (d == 1 && dims <= 2)) && _type == type() )
    {
        if( d == 2 && rows == _sizes[0] && cols == _sizes[1] )
            return;
        for( i = 0; i < d; i++ )
            if( size[i] != _sizes[i] )
                break;
        if( i == d && (d > 1 || size[1] == 1))
            return;
    }
679

680 681 682 683 684 685 686 687
    int _sizes_backup[CV_MAX_DIM]; // #5991
    if (_sizes == (this->size.p))
    {
        for(i = 0; i < d; i++ )
            _sizes_backup[i] = _sizes[i];
        _sizes = _sizes_backup;
    }

V
Vadim Pisarevsky 已提交
688 689 690 691
    release();
    if( d == 0 )
        return;
    flags = (_type & CV_MAT_TYPE_MASK) | MAGIC_VAL;
692
    setSize(*this, d, _sizes, 0, true);
693

694
    if( total() > 0 )
V
Vadim Pisarevsky 已提交
695
    {
696
        MatAllocator *a = allocator, *a0 = getDefaultAllocator();
A
Andrey Pavlenko 已提交
697
#ifdef HAVE_TGPU
698 699
        if( !a || a == tegra::getAllocator() )
            a = tegra::getAllocator(d, _sizes, _type);
A
Andrey Pavlenko 已提交
700
#endif
701 702
        if(!a)
            a = a0;
703
        try
704
        {
705
            u = a->allocate(dims, size, _type, 0, step.p, ACCESS_RW /* ignored */, USAGE_DEFAULT);
706
            CV_Assert(u != 0);
707
        }
708
        catch (...)
709
        {
710 711
            if (a == a0)
                throw;
712
            u = a0->allocate(dims, size, _type, 0, step.p, ACCESS_RW /* ignored */, USAGE_DEFAULT);
713
            CV_Assert(u != 0);
714
        }
715
        CV_Assert( step[dims-1] == (size_t)CV_ELEM_SIZE(flags) );
V
Vadim Pisarevsky 已提交
716
    }
717

A
Alexander Alekhin 已提交
718
    addref();
V
Vadim Pisarevsky 已提交
719 720 721
    finalizeHdr(*this);
}

722 723 724 725 726
void Mat::create(const std::vector<int>& _sizes, int _type)
{
    create((int)_sizes.size(), _sizes.data(), _type);
}

V
Vadim Pisarevsky 已提交
727 728 729 730 731 732 733 734 735
void Mat::copySize(const Mat& m)
{
    setSize(*this, m.dims, 0, 0);
    for( int i = 0; i < dims; i++ )
    {
        size[i] = m.size[i];
        step[i] = m.step[i];
    }
}
736

V
Vadim Pisarevsky 已提交
737 738
void Mat::deallocate()
{
739
    if(u)
740 741 742 743 744
    {
        UMatData* u_ = u;
        u = NULL;
        (u_->currAllocator ? u_->currAllocator : allocator ? allocator : getDefaultAllocator())->unmap(u_);
    }
V
Vadim Pisarevsky 已提交
745 746
}

A
Andrey Kamaev 已提交
747
Mat::Mat(const Mat& m, const Range& _rowRange, const Range& _colRange)
748 749
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows)
V
Vadim Pisarevsky 已提交
750 751 752 753 754
{
    CV_Assert( m.dims >= 2 );
    if( m.dims > 2 )
    {
        AutoBuffer<Range> rs(m.dims);
A
Andrey Kamaev 已提交
755 756
        rs[0] = _rowRange;
        rs[1] = _colRange;
V
Vadim Pisarevsky 已提交
757 758
        for( int i = 2; i < m.dims; i++ )
            rs[i] = Range::all();
759
        *this = m(rs.data());
V
Vadim Pisarevsky 已提交
760 761
        return;
    }
762

V
Vadim Pisarevsky 已提交
763
    *this = m;
A
Alexander Alekhin 已提交
764
    try
V
Vadim Pisarevsky 已提交
765
    {
766 767 768 769 770 771 772 773
        if( _rowRange != Range::all() && _rowRange != Range(0,rows) )
        {
            CV_Assert( 0 <= _rowRange.start && _rowRange.start <= _rowRange.end
                       && _rowRange.end <= m.rows );
            rows = _rowRange.size();
            data += step*_rowRange.start;
            flags |= SUBMATRIX_FLAG;
        }
774

775 776 777 778 779 780 781 782 783
        if( _colRange != Range::all() && _colRange != Range(0,cols) )
        {
            CV_Assert( 0 <= _colRange.start && _colRange.start <= _colRange.end
                       && _colRange.end <= m.cols );
            cols = _colRange.size();
            data += _colRange.start*elemSize();
            flags |= SUBMATRIX_FLAG;
        }
    }
A
Alexander Alekhin 已提交
784
    catch(...)
V
Vadim Pisarevsky 已提交
785
    {
786
        release();
A
Alexander Alekhin 已提交
787
        throw;
V
Vadim Pisarevsky 已提交
788
    }
789

790
    updateContinuityFlag();
791

V
Vadim Pisarevsky 已提交
792 793 794 795 796 797
    if( rows <= 0 || cols <= 0 )
    {
        release();
        rows = cols = 0;
    }
}
798 799


V
Vadim Pisarevsky 已提交
800 801
Mat::Mat(const Mat& m, const Rect& roi)
    : flags(m.flags), dims(2), rows(roi.height), cols(roi.width),
802
    data(m.data + roi.y*m.step[0]),
803
    datastart(m.datastart), dataend(m.dataend), datalimit(m.datalimit),
804
    allocator(m.allocator), u(m.u), size(&rows)
V
Vadim Pisarevsky 已提交
805 806
{
    CV_Assert( m.dims <= 2 );
807

808
    size_t esz = CV_ELEM_SIZE(flags);
V
Vadim Pisarevsky 已提交
809 810 811
    data += roi.x*esz;
    CV_Assert( 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols &&
              0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows );
812 813
    if( roi.width < m.cols || roi.height < m.rows )
        flags |= SUBMATRIX_FLAG;
814

V
Vadim Pisarevsky 已提交
815
    step[0] = m.step[0]; step[1] = esz;
816
    updateContinuityFlag();
817

818
    addref();
V
Vadim Pisarevsky 已提交
819 820 821
    if( rows <= 0 || cols <= 0 )
    {
        rows = cols = 0;
822
        release();
V
Vadim Pisarevsky 已提交
823 824 825
    }
}

826

A
Andrey Kamaev 已提交
827
Mat::Mat(int _dims, const int* _sizes, int _type, void* _data, const size_t* _steps)
828 829
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows)
V
Vadim Pisarevsky 已提交
830
{
831
    flags |= CV_MAT_TYPE(_type);
832
    datastart = data = (uchar*)_data;
V
Vadim Pisarevsky 已提交
833 834 835
    setSize(*this, _dims, _sizes, _steps, true);
    finalizeHdr(*this);
}
836 837


838 839 840 841 842 843 844 845 846 847 848
Mat::Mat(const std::vector<int>& _sizes, int _type, void* _data, const size_t* _steps)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows)
{
    flags |= CV_MAT_TYPE(_type);
    datastart = data = (uchar*)_data;
    setSize(*this, (int)_sizes.size(), _sizes.data(), _steps, true);
    finalizeHdr(*this);
}


A
Andrey Kamaev 已提交
849
Mat::Mat(const Mat& m, const Range* ranges)
850 851
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
      datalimit(0), allocator(0), u(0), size(&rows)
V
Vadim Pisarevsky 已提交
852
{
853
    int d = m.dims;
854

V
Vadim Pisarevsky 已提交
855
    CV_Assert(ranges);
856
    for( int i = 0; i < d; i++ )
V
Vadim Pisarevsky 已提交
857 858 859 860 861
    {
        Range r = ranges[i];
        CV_Assert( r == Range::all() || (0 <= r.start && r.start < r.end && r.end <= m.size[i]) );
    }
    *this = m;
862
    for( int i = 0; i < d; i++ )
V
Vadim Pisarevsky 已提交
863 864
    {
        Range r = ranges[i];
865
        if( r != Range::all() && r != Range(0, size.p[i]))
V
Vadim Pisarevsky 已提交
866
        {
867 868 869
            size.p[i] = r.end - r.start;
            data += r.start*step.p[i];
            flags |= SUBMATRIX_FLAG;
V
Vadim Pisarevsky 已提交
870 871
        }
    }
872
    updateContinuityFlag();
V
Vadim Pisarevsky 已提交
873
}
874

875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
Mat::Mat(const Mat& m, const std::vector<Range>& ranges)
    : flags(MAGIC_VAL), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0),
    datalimit(0), allocator(0), u(0), size(&rows)
{
    int d = m.dims;

    CV_Assert((int)ranges.size() == d);
    for (int i = 0; i < d; i++)
    {
        Range r = ranges[i];
        CV_Assert(r == Range::all() || (0 <= r.start && r.start < r.end && r.end <= m.size[i]));
    }
    *this = m;
    for (int i = 0; i < d; i++)
    {
        Range r = ranges[i];
        if (r != Range::all() && r != Range(0, size.p[i]))
        {
            size.p[i] = r.end - r.start;
            data += r.start*step.p[i];
            flags |= SUBMATRIX_FLAG;
        }
    }
898
    updateContinuityFlag();
899
}
900 901


A
Andrey Kamaev 已提交
902
Mat Mat::diag(int d) const
903
{
V
Vadim Pisarevsky 已提交
904
    CV_Assert( dims <= 2 );
A
Andrey Kamaev 已提交
905 906 907
    Mat m = *this;
    size_t esz = elemSize();
    int len;
908

A
Andrey Kamaev 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    if( d >= 0 )
    {
        len = std::min(cols - d, rows);
        m.data += esz*d;
    }
    else
    {
        len = std::min(rows + d, cols);
        m.data -= step[0]*d;
    }
    CV_DbgAssert( len > 0 );

    m.size[0] = m.rows = len;
    m.size[1] = m.cols = 1;
    m.step[0] += (len > 1 ? esz : 0);

925
    m.updateContinuityFlag();
A
Andrey Kamaev 已提交
926 927 928 929 930 931

    if( size() != Size(1,1) )
        m.flags |= SUBMATRIX_FLAG;

    return m;
}
932

933

934 935 936
void Mat::pop_back(size_t nelems)
{
    CV_Assert( nelems <= (size_t)size.p[0] );
937

938 939 940 941 942 943 944 945
    if( isSubmatrix() )
        *this = rowRange(0, size.p[0] - (int)nelems);
    else
    {
        size.p[0] -= (int)nelems;
        dataend -= nelems*step.p[0];
    }
}
946 947


948 949
void Mat::push_back_(const void* elem)
{
950
    size_t r = size.p[0];
951 952
    if( isSubmatrix() || dataend + step.p[0] > datalimit )
        reserve( std::max(r + 1, (r*3+1)/2) );
953

954 955
    size_t esz = elemSize();
    memcpy(data + r*step.p[0], elem, esz);
956
    size.p[0] = int(r + 1);
957
    dataend += step.p[0];
958 959 960 961
    uint64 tsz = size.p[0];
    for( int i = 1; i < dims; i++ )
        tsz *= size.p[i];
    if( esz < step.p[0] || tsz != (uint64)(int)tsz )
962 963 964
        flags &= ~CONTINUOUS_FLAG;
}

965

966 967 968
void Mat::reserve(size_t nelems)
{
    const size_t MIN_SIZE = 64;
969

970 971 972
    CV_Assert( (int)nelems >= 0 );
    if( !isSubmatrix() && data + step.p[0]*nelems <= datalimit )
        return;
973

974
    int r = size.p[0];
975

976 977
    if( (size_t)r >= nelems )
        return;
978

979 980
    size.p[0] = std::max((int)nelems, 1);
    size_t newsize = total()*elemSize();
981

982 983
    if( newsize < MIN_SIZE )
        size.p[0] = (int)((MIN_SIZE + newsize - 1)*nelems/newsize);
984

985 986 987 988 989 990 991
    Mat m(dims, size.p, type());
    size.p[0] = r;
    if( r > 0 )
    {
        Mat mpart = m.rowRange(0, r);
        copyTo(mpart);
    }
992

993 994 995 996 997
    *this = m;
    size.p[0] = r;
    dataend = data + step.p[0]*r;
}

998

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
void Mat::reserveBuffer(size_t nbytes)
{
    size_t esz = 1;
    int mtype = CV_8UC1;
    if (!empty())
    {
        if (!isSubmatrix() && data + nbytes <= dataend)//Should it be datalimit?
            return;
        esz = elemSize();
        mtype = type();
    }

    size_t nelems = (nbytes - 1) / esz + 1;

#if SIZE_MAX > UINT_MAX
    CV_Assert(nelems <= size_t(INT_MAX)*size_t(INT_MAX));
    int newrows = nelems > size_t(INT_MAX) ? nelems > 0x400*size_t(INT_MAX) ? nelems > 0x100000 * size_t(INT_MAX) ? nelems > 0x40000000 * size_t(INT_MAX) ?
                  size_t(INT_MAX) : 0x40000000 : 0x100000 : 0x400 : 1;
#else
    int newrows = nelems > size_t(INT_MAX) ? 2 : 1;
#endif
    int newcols = (int)((nelems - 1) / newrows + 1);

    create(newrows, newcols, mtype);
}

1025

1026 1027 1028
void Mat::resize(size_t nelems)
{
    int saveRows = size.p[0];
1029 1030
    if( saveRows == (int)nelems )
        return;
1031
    CV_Assert( (int)nelems >= 0 );
1032

1033 1034
    if( isSubmatrix() || data + step.p[0]*nelems > datalimit )
        reserve(nelems);
1035

1036 1037
    size.p[0] = (int)nelems;
    dataend += (size.p[0] - saveRows)*step.p[0];
1038

1039
    //updateContinuityFlag(*this);
1040 1041
}

1042 1043 1044 1045 1046

void Mat::resize(size_t nelems, const Scalar& s)
{
    int saveRows = size.p[0];
    resize(nelems);
1047

1048 1049 1050 1051 1052
    if( size.p[0] > saveRows )
    {
        Mat part = rowRange(saveRows, size.p[0]);
        part = s;
    }
1053 1054
}

1055 1056
void Mat::push_back(const Mat& elems)
{
1057 1058
    size_t r = size.p[0];
    size_t delta = elems.size.p[0];
1059 1060
    if( delta == 0 )
        return;
1061 1062 1063 1064 1065
    if( this == &elems )
    {
        Mat tmp = elems;
        push_back(tmp);
        return;
1066
    }
1067 1068 1069 1070 1071
    if( !data )
    {
        *this = elems.clone();
        return;
    }
1072 1073 1074

    size.p[0] = elems.size.p[0];
    bool eq = size == elems.size;
1075
    size.p[0] = int(r);
1076
    if( !eq )
I
Ilya Lavrenov 已提交
1077
        CV_Error(CV_StsUnmatchedSizes, "Pushed vector length is not equal to matrix row length");
1078
    if( type() != elems.type() )
I
Ilya Lavrenov 已提交
1079
        CV_Error(CV_StsUnmatchedFormats, "Pushed vector type is not the same as matrix type");
1080

1081 1082
    if( isSubmatrix() || dataend + step.p[0]*delta > datalimit )
        reserve( std::max(r + delta, (r*3+1)/2) );
1083

1084
    size.p[0] += int(delta);
1085
    dataend += step.p[0]*delta;
1086

1087
    //updateContinuityFlag(*this);
1088

1089 1090 1091 1092
    if( isContinuous() && elems.isContinuous() )
        memcpy(data + r*step.p[0], elems.data, elems.total()*elems.elemSize());
    else
    {
1093
        Mat part = rowRange(int(r), int(r + delta));
1094 1095 1096 1097
        elems.copyTo(part);
    }
}

1098

V
Vadim Pisarevsky 已提交
1099 1100 1101 1102 1103
void Mat::locateROI( Size& wholeSize, Point& ofs ) const
{
    CV_Assert( dims <= 2 && step[0] > 0 );
    size_t esz = elemSize(), minstep;
    ptrdiff_t delta1 = data - datastart, delta2 = dataend - datastart;
1104

V
Vadim Pisarevsky 已提交
1105 1106
    if( delta1 == 0 )
        ofs.x = ofs.y = 0;
1107 1108
    else
    {
V
Vadim Pisarevsky 已提交
1109 1110 1111
        ofs.y = (int)(delta1/step[0]);
        ofs.x = (int)((delta1 - step[0]*ofs.y)/esz);
        CV_DbgAssert( data == datastart + ofs.y*step[0] + ofs.x*esz );
1112
    }
V
Vadim Pisarevsky 已提交
1113 1114 1115 1116 1117
    minstep = (ofs.x + cols)*esz;
    wholeSize.height = (int)((delta2 - minstep)/step[0] + 1);
    wholeSize.height = std::max(wholeSize.height, ofs.y + rows);
    wholeSize.width = (int)((delta2 - step*(wholeSize.height-1))/esz);
    wholeSize.width = std::max(wholeSize.width, ofs.x + cols);
1118 1119
}

V
Vadim Pisarevsky 已提交
1120 1121 1122 1123 1124 1125
Mat& Mat::adjustROI( int dtop, int dbottom, int dleft, int dright )
{
    CV_Assert( dims <= 2 && step[0] > 0 );
    Size wholeSize; Point ofs;
    size_t esz = elemSize();
    locateROI( wholeSize, ofs );
1126 1127 1128 1129 1130 1131 1132
    int row1 = std::min(std::max(ofs.y - dtop, 0), wholeSize.height), row2 = std::max(0, std::min(ofs.y + rows + dbottom, wholeSize.height));
    int col1 = std::min(std::max(ofs.x - dleft, 0), wholeSize.width), col2 = std::max(0, std::min(ofs.x + cols + dright, wholeSize.width));
    if(row1 > row2)
        std::swap(row1, row2);
    if(col1 > col2)
        std::swap(col1, col2);

V
Vadim Pisarevsky 已提交
1133 1134 1135
    data += (row1 - ofs.y)*step + (col1 - ofs.x)*esz;
    rows = row2 - row1; cols = col2 - col1;
    size.p[0] = rows; size.p[1] = cols;
1136
    updateContinuityFlag();
V
Vadim Pisarevsky 已提交
1137
    return *this;
1138
}
1139

1140 1141 1142
Mat Mat::reshape(int new_cn, int new_rows) const
{
    int cn = channels();
1143
    Mat hdr = *this;
1144

1145
    if( dims > 2 )
1146
    {
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
        if( new_rows == 0 && new_cn != 0 && size[dims-1]*cn % new_cn == 0 )
        {
            hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((new_cn-1) << CV_CN_SHIFT);
            hdr.step[dims-1] = CV_ELEM_SIZE(hdr.flags);
            hdr.size[dims-1] = hdr.size[dims-1]*cn / new_cn;
            return hdr;
        }
        if( new_rows > 0 )
        {
            int sz[] = { new_rows, (int)(total()/new_rows) };
            return reshape(new_cn, 2, sz);
        }
1159
    }
1160

1161
    CV_Assert( dims <= 2 );
1162

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    if( new_cn == 0 )
        new_cn = cn;

    int total_width = cols * cn;

    if( (new_cn > total_width || total_width % new_cn != 0) && new_rows == 0 )
        new_rows = rows * total_width / new_cn;

    if( new_rows != 0 && new_rows != rows )
    {
        int total_size = total_width * rows;
        if( !isContinuous() )
            CV_Error( CV_BadStep,
            "The matrix is not continuous, thus its number of rows can not be changed" );

        if( (unsigned)new_rows > (unsigned)total_size )
            CV_Error( CV_StsOutOfRange, "Bad new number of rows" );

        total_width = total_size / new_rows;

        if( total_width * new_rows != total_size )
            CV_Error( CV_StsBadArg, "The total number of matrix elements "
                                    "is not divisible by the new number of rows" );

        hdr.rows = new_rows;
V
Vadim Pisarevsky 已提交
1188
        hdr.step[0] = total_width * elemSize1();
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
    }

    int new_width = total_width / new_cn;

    if( new_width * new_cn != total_width )
        CV_Error( CV_BadNumChannels,
        "The total width is not divisible by the new number of channels" );

    hdr.cols = new_width;
    hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((new_cn-1) << CV_CN_SHIFT);
1199
    hdr.step[1] = CV_ELEM_SIZE(hdr.flags);
1200 1201 1202
    return hdr;
}

1203
Mat Mat::reshape(int _cn, int _newndims, const int* _newsz) const
1204
{
1205
    if(_newndims == dims)
1206
    {
1207 1208 1209 1210
        if(_newsz == 0)
            return reshape(_cn);
        if(_newndims == 2)
            return reshape(_cn, _newsz[0]);
1211
    }
1212

1213
    if (isContinuous())
1214
    {
1215
        CV_Assert(_cn >= 0 && _newndims > 0 && _newndims <= CV_MAX_DIM && _newsz);
1216

1217 1218 1219 1220
        if (_cn == 0)
            _cn = this->channels();
        else
            CV_Assert(_cn <= CV_CN_MAX);
1221

1222 1223
        size_t total_elem1_ref = this->total() * this->channels();
        size_t total_elem1 = _cn;
1224

1225
        AutoBuffer<int, 4> newsz_buf( (size_t)_newndims );
1226

1227 1228 1229
        for (int i = 0; i < _newndims; i++)
        {
            CV_Assert(_newsz[i] >= 0);
1230

1231 1232 1233 1234 1235 1236
            if (_newsz[i] > 0)
                newsz_buf[i] = _newsz[i];
            else if (i < dims)
                newsz_buf[i] = this->size[i];
            else
                CV_Error(CV_StsOutOfRange, "Copy dimension (which has zero size) is not present in source matrix");
1237

1238 1239
            total_elem1 *= (size_t)newsz_buf[i];
        }
1240

1241 1242
        if (total_elem1 != total_elem1_ref)
            CV_Error(CV_StsUnmatchedSizes, "Requested and source matrices have different count of elements");
1243

1244 1245
        Mat hdr = *this;
        hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((_cn-1) << CV_CN_SHIFT);
1246
        setSize(hdr, _newndims, newsz_buf.data(), NULL, true);
1247

1248
        return hdr;
1249
    }
1250

1251 1252
    CV_Error(CV_StsNotImplemented, "Reshaping of n-dimensional non-continuous matrices is not supported yet");
    // TBD
1253 1254
}

1255
Mat Mat::reshape(int _cn, const std::vector<int>& _newshape) const
1256
{
1257
    if(_newshape.empty())
1258
    {
1259 1260
        CV_Assert(empty());
        return *this;
1261 1262
    }

1263
    return reshape(_cn, (int)_newshape.size(), &_newshape[0]);
1264
}
1265

1266
Mat Mat::diag(const Mat& d)
1267
{
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    CV_Assert( d.cols == 1 || d.rows == 1 );
    int len = d.rows + d.cols - 1;
    Mat m(len, len, d.type(), Scalar(0));
    Mat md = m.diag();
    if( d.cols == 1 )
        d.copyTo(md);
    else
        transpose(d, md);
    return m;
}
1278

1279
int Mat::checkVector(int _elemChannels, int _depth, bool _requireContinuous) const
A
Andrey Kamaev 已提交
1280
{
1281 1282 1283 1284 1285 1286 1287
    return data && (depth() == _depth || _depth <= 0) &&
        (isContinuous() || !_requireContinuous) &&
        ((dims == 2 && (((rows == 1 || cols == 1) && channels() == _elemChannels) ||
                        (cols == _elemChannels && channels() == 1))) ||
        (dims == 3 && channels() == 1 && size.p[2] == _elemChannels && (size.p[0] == 1 || size.p[1] == 1) &&
         (isContinuous() || step.p[1] == step.p[2]*size.p[2])))
    ? (int)(total()*channels()/_elemChannels) : -1;
A
Andrey Kamaev 已提交
1288 1289
}

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362

static inline Size getContinuousSize_(int flags, int cols, int rows, int widthScale)
{
    int64 sz = (int64)cols * rows * widthScale;
    bool has_int_overflow = sz >= INT_MAX;
    bool isContiguous = (flags & Mat::CONTINUOUS_FLAG) != 0;
    return (isContiguous && !has_int_overflow)
            ? Size((int)sz, 1)
            : Size(cols * widthScale, rows);
}

Size getContinuousSize2D(Mat& m1, int widthScale)
{
    CV_CheckLE(m1.dims, 2, "");
    return getContinuousSize_(m1.flags,
                              m1.cols, m1.rows, widthScale);
}
Size getContinuousSize2D(Mat& m1, Mat& m2, int widthScale)
{
    CV_CheckLE(m1.dims, 2, "");
    CV_CheckLE(m2.dims, 2, "");
    const Size sz1 = m1.size();
    if (sz1 != m2.size())  // reshape all matrixes to the same size (#4159)
    {
        size_t total_sz = m1.total();
        CV_CheckEQ(total_sz, m2.total(), "");
        bool is_m1_vector = m1.cols == 1 || m1.rows == 1;
        bool is_m2_vector = m2.cols == 1 || m2.rows == 1;
        CV_Assert(is_m1_vector); CV_Assert(is_m2_vector);
        int total = (int)total_sz;  // vector-column
        bool isContiguous = ((m1.flags & m2.flags) & Mat::CONTINUOUS_FLAG) != 0;
        bool has_int_overflow = ((int64)total_sz * widthScale) >= INT_MAX;
        if (isContiguous && !has_int_overflow)
            total = 1; // vector-row
        m1 = m1.reshape(0, total);
        m2 = m2.reshape(0, total);
        CV_Assert(m1.cols == m2.cols && m1.rows == m2.rows);
        return Size(m1.cols * widthScale, m1.rows);
    }
    return getContinuousSize_(m1.flags & m2.flags,
                              m1.cols, m1.rows, widthScale);
}

Size getContinuousSize2D(Mat& m1, Mat& m2, Mat& m3, int widthScale)
{
    CV_CheckLE(m1.dims, 2, "");
    CV_CheckLE(m2.dims, 2, "");
    CV_CheckLE(m3.dims, 2, "");
    const Size sz1 = m1.size();
    if (sz1 != m2.size() || sz1 != m3.size())  // reshape all matrixes to the same size (#4159)
    {
        size_t total_sz = m1.total();
        CV_CheckEQ(total_sz, m2.total(), "");
        CV_CheckEQ(total_sz, m3.total(), "");
        bool is_m1_vector = m1.cols == 1 || m1.rows == 1;
        bool is_m2_vector = m2.cols == 1 || m2.rows == 1;
        bool is_m3_vector = m3.cols == 1 || m3.rows == 1;
        CV_Assert(is_m1_vector); CV_Assert(is_m2_vector); CV_Assert(is_m3_vector);
        int total = (int)total_sz;  // vector-column
        bool isContiguous = ((m1.flags & m2.flags & m3.flags) & Mat::CONTINUOUS_FLAG) != 0;
        bool has_int_overflow = ((int64)total_sz * widthScale) >= INT_MAX;
        if (isContiguous && !has_int_overflow)
            total = 1; // vector-row
        m1 = m1.reshape(0, total);
        m2 = m2.reshape(0, total);
        m3 = m3.reshape(0, total);
        CV_Assert(m1.cols == m2.cols && m1.rows == m2.rows && m1.cols == m3.cols && m1.rows == m3.rows);
        return Size(m1.cols * widthScale, m1.rows);
    }
    return getContinuousSize_(m1.flags & m2.flags & m3.flags,
                              m1.cols, m1.rows, widthScale);
}

1363
} // cv::