Post date: Apr 05, 2017 5:36:29 AM
This current example is based on a cv::Mat(r, 1, CV_8UC1) or uchar vector. There is no reason that it cannot be extended to larger cv::Mat;s but I am not testing that because for the moment, I am only interested in vectors made from cv::Mat's. std::map is defined in http://www.cplusplus.com/reference/map/map/ .The key value we want is cv::Mat. For example purposes, the Value can be double. According to the documentation, we need a Key compare. Say matcompare. So the type is called std::map<cv::Mat, double, matcompare>. matcompare is a function that provides a "lessthan" comparison for the keys to order them in the map as well as to identify the Key-Value pair. I define matcompare like this
struct matcompare {
bool operator()(const cv::Mat& lhs, const cv::Mat& rhs) const
{
uchar* src1ptr = lhs.data;
uchar* src2ptr = rhs.data;
bool ands = true;
bool lessthan = false;
for (int i = 0; i < lhs.rows; i++)
{
lessthan = (*((uchar*)(src1ptr + i * lhs.step)) < *((uchar *)(src2ptr + i * rhs.step))) && ands;
if (lessthan)
break;
ands = (*((uchar*)(src1ptr + i * lhs.step)) == *((uchar *)(src2ptr + i * rhs.step))) && ands;
}
return lessthan;
}
};
The meaning of "lessthan" needs to be defined so I arbitrarily define it as returning true if the lowest indexed element fulfills the lessthan condition. The pointer work is just so that I squeeze out more speed. They are just replacements of for example lhs->at<uchar>(i, 0). The code to test this is
int main(int argc, char** argv)
{
std::map <cv::Mat, double, matcompare>* mymap = new std::map<cv::Mat, double, matcompare>();
cv::Mat b1 = (cv::Mat_<uchar>(3, 1) << 2, 4, 7);
cv::Mat b2 = (cv::Mat_<uchar>(3, 1) << 3, 2, 7);
cv::Mat b3 = (cv::Mat_<uchar>(3, 1) << 1, 2, 3);
cv::Mat b4 = (cv::Mat_<uchar>(3, 1) << 3, 2, 5);
cv::Mat b5 = (cv::Mat_<uchar>(3, 1) << 2, 4, 7);
(*mymap)[b1] = 1.0;
(*mymap)[b2] = 2.0;
(*mymap)[b3] = 3.0;
(*mymap)[b4] = 4.0;
std::cout << "Size of map is " << mymap->size() << std::endl;
DisplayMap(mymap);
(*mymap)[b5] += 1.0;
std::cout << "Size of map is " << mymap->size() << std::endl;
DisplayMap(mymap);
std::getchar();
return 0;
}
DisplayMap is just a routine to iterate through the referenced map. The output is
Size of map is 4
[ 1, 2, 3] 3
[ 2, 4, 7] 1
[ 3, 2, 5] 4
[ 3, 2, 7] 2
Size of map is 4
[ 1, 2, 3] 3
[ 2, 4, 7] 2
[ 3, 2, 5] 4
[ 3, 2, 7] 2