Skip to content

Commit 6c1247b

Browse files
committed
fix#9570: implement mat ptr for generic types
The original template based mat ptr for indexing is not implemented, add the similar implementation as uchar type, but cast to user-defined type from the uchar pointer.
1 parent 92a0808 commit 6c1247b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

modules/core/include/opencv2/core/mat.inl.hpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1058,6 +1058,34 @@ const uchar* Mat::ptr(const int* idx) const
10581058
return p;
10591059
}
10601060

1061+
template<typename _Tp> inline
1062+
_Tp* Mat::ptr(const int* idx)
1063+
{
1064+
int i, d = dims;
1065+
uchar* p = data;
1066+
CV_DbgAssert( d >= 1 && p );
1067+
for( i = 0; i < d; i++ )
1068+
{
1069+
CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] );
1070+
p += idx[i] * step.p[i];
1071+
}
1072+
return (_Tp*)p;
1073+
}
1074+
1075+
template<typename _Tp> inline
1076+
const _Tp* Mat::ptr(const int* idx) const
1077+
{
1078+
int i, d = dims;
1079+
uchar* p = data;
1080+
CV_DbgAssert( d >= 1 && p );
1081+
for( i = 0; i < d; i++ )
1082+
{
1083+
CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] );
1084+
p += idx[i] * step.p[i];
1085+
}
1086+
return (const _Tp*)p;
1087+
}
1088+
10611089
template<typename _Tp> inline
10621090
_Tp& Mat::at(int i0, int i1)
10631091
{

modules/core/test/test_mat.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1804,4 +1804,24 @@ TEST(Mat_, from_initializer_list)
18041804
ASSERT_DOUBLE_EQ(norm(A, B, NORM_INF), 0.);
18051805
}
18061806

1807+
1808+
TEST(Mat, template_based_ptr)
1809+
{
1810+
Mat mat = (Mat_<float>(2, 2) << 11.0f, 22.0f, 33.0f, 44.0f);
1811+
int idx[2] = {1, 0};
1812+
ASSERT_FLOAT_EQ(33.0f, *(mat.ptr<float>(idx)));
1813+
idx[0] = 1;
1814+
idx[1] = 1;
1815+
ASSERT_FLOAT_EQ(44.0f, *(mat.ptr<float>(idx)));
1816+
}
1817+
1818+
TEST(Mat_, template_based_ptr)
1819+
{
1820+
int dim[4] = {2, 2, 1, 2};
1821+
Mat_<float> mat = (Mat_<float>(4, dim) << 11.0f, 22.0f, 33.0f, 44.0f,
1822+
55.0f, 66.0f, 77.0f, 88.0f);
1823+
int idx[4] = {1, 0, 0, 1};
1824+
ASSERT_FLOAT_EQ(66.0f, *(mat.ptr<float>(idx)));
1825+
}
1826+
18071827
#endif

0 commit comments

Comments
 (0)