如果我有一个Mat的像素值,我如何在另一个Mat中找到相同像素值的位置(坐标)?
答案 0 :(得分:2)
以下内容提供find()
,它会将特定值的Mat中的位置作为点向量返回。简短的演示main()
表明它适用于彩色和灰度图像。
#include <opencv2/core/core.hpp>
#include <iostream> // std::cout
#include <vector> // std::vector
template<typename _Tp>
std::vector<cv::Point> inline find(_Tp key, cv::Mat M)
{
int pos = 0;
std::vector<cv::Point> result;
std::for_each(M.begin<_Tp>(), M.end<_Tp>(), [&](_Tp & m)
{
if(m == key)
{
cv::Point p(pos % M.cols, pos / M.cols);
result.push_back(p);
}
pos ++;
});
return result;
}
int main(int argc, char** argv)
{
uchar data[] = {1, 2, 3, 4, 5, 6, 8, 9, 0,
8, 9, 0, 4, 5, 6, 1, 2, 3,
1, 2, 3, 8, 9, 0, 4, 5, 6,
7, 8, 9, 3, 4, 5, 3, 4, 5};
cv::Mat M1(4, 9, CV_8UC1, data);
uchar key1(1);
std::vector<cv::Point> vp = find(key1, M1);
std::cout << "key " << int(key1) << " was found in the Mat" << std::endl;
std::cout << M1 << std::endl << "at" << std::endl;
for(cv::Point p : vp) // print where key is found in M
{
std::cout << p << std::endl;
}
cv::Mat M3(4, 3, CV_8UC3, data);
cv::Vec3b key3(8, 9, 0);
vp = find(key3, M3);
std::cout << std::endl;
std::cout << "key " << key3 << " was found in the Mat" << std::endl;
std::cout << M3 << std::endl << "at" << std::endl;
for(cv::Point p : vp) // print where key is found in M
{
std::cout << p << std::endl;
}
return 0;
}