Skip to content

Commit 68f5272

Browse files
authored
Merge pull request opencv#18080 from nhlsm:improve-mat-operator-assign-scalar
* improve Mat::operator=(Scalar) * touch * remove trailing whitespace * TEST: check if old code pass test or not * remove CV_Error * remove warning * fix: is -> Scalar * 1) Mat *mat -> Mat &mat 2) return bool, add output param * add comment
1 parent 7f22b34 commit 68f5272

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

modules/core/src/copy.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,29 @@ void Mat::copyTo( OutputArray _dst, InputArray _mask ) const
414414
copymask(ptrs[0], 0, ptrs[2], 0, ptrs[1], 0, sz, &esz);
415415
}
416416

417+
418+
static bool can_apply_memset(const Mat &mat, const Scalar &s, int &fill_value)
419+
{
420+
// check if depth is 1 byte.
421+
switch (mat.depth())
422+
{
423+
case CV_8U: fill_value = saturate_cast<uchar>( s.val[0] ); break;
424+
case CV_8S: fill_value = saturate_cast<schar>( s.val[0] ); break;
425+
default: return false;
426+
}
427+
428+
// check if all element is same.
429+
const int64* is = (const int64*)&s.val[0];
430+
switch (mat.channels())
431+
{
432+
case 1: return true;
433+
case 2: return (is[0] == is[1]);
434+
case 3: return (is[0] == is[1] && is[1] == is[2]);
435+
case 4: return (is[0] == is[1] && is[1] == is[2] && is[2] == is[3]);
436+
default: return false;
437+
}
438+
}
439+
417440
Mat& Mat::operator = (const Scalar& s)
418441
{
419442
CV_INSTRUMENT_REGION();
@@ -434,6 +457,14 @@ Mat& Mat::operator = (const Scalar& s)
434457
}
435458
else
436459
{
460+
int fill_value = 0;
461+
if ( can_apply_memset(*this, s, fill_value) )
462+
{
463+
for (size_t i = 0; i < it.nplanes; i++, ++it)
464+
memset(dptr, fill_value, elsize);
465+
return *this;
466+
}
467+
437468
if( it.nplanes > 0 )
438469
{
439470
double scalar[12];

0 commit comments

Comments
 (0)