如果我从一个Mat中获得一个像素值,如何在另一个Mat中找到相同像素值的位置(坐标)?
最佳答案
以下内容提供了find()
,它将返回Mat中具有特定值的位置作为点 vector 。简短的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;
}
关于c++ - 如何在Mat中查找指定值,以及在另一个Mat中查找其对应值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20100704/