将值映射到像素对-如何实现数据结构
Mapping value to pixel pairs - How to implement the data structure
我有一个函数f(x,y),其中x和y是像素坐标(如OpenCV cv::Point(i,j)
),将浮点值映射到每个像素对(x,y)。我的问题是:表示这种映射的正确数据结构是什么?我想要一个具有多种类型的数组,这在标准数组中是不可能的。我想在下面的例子中使用它:
mat[cv::Point(i,j)][cv::Point(k,l)] = 5.0f;
正如@Gombat已经提到的,一个简单的方法是使用std::map
,并使用std::pair<cv::Point, cv::Point>
作为键。
。由于cv::Point
不提供operator<
,因此需要提供自定义比较器。
看一下这段代码:
#include <opencv2/opencv.hpp>
#include <map>
using namespace cv;
using namespace std;
bool lessPoints(const Point& lhs, const Point& rhs)
{
return (lhs.x == rhs.x) ? lhs.y < rhs.y : lhs.x < rhs.x;
}
struct lessPairPoints
{
bool operator()(const pair<Point, Point>& lhs, const pair<Point, Point>& rhs) const
{
return (lhs.first == rhs.first) ? lessPoints(lhs.second, rhs.second) : lessPoints(lhs.first, rhs.first);
}
};
typedef map<pair<Point, Point>, float, lessPairPoints> MapPoints;
int main()
{
MapPoints map1;
map1[{Point(0, 0), Point(1, 1)}] = 0.3;
map1[{Point(1, 2), Point(1, 1)}] = 0.1;
for (const auto& el : map1)
{
cout << el.first.first << ", " << el.first.second << " -> " << el.second << endl;
}
cout << map1[{Point(0,0), Point(1,1)}] << endl;
auto pp = make_pair(Point(1,2), Point(1,1));
cout << map1[pp] << endl;
return 0;
}
可以使用std::map
:
std::map< Point, std::map< Point, float > > map;
map[Point(0,0)][Point(0,0)] = 5.0f;
但要做到这一点,Point
需要operator<
:
struct Point
{
Point(const size_t _x, const size_t _y) : x(_x), y(_y) {}
size_t x, y;
bool operator<(const Point& rhs) const
{
// first of all, order regarding x
if ( x < rhs.x ) return true;
if ( x > rhs.x ) return false;
// if x is equal, order regarding y
if ( y < rhs.y ) return true;
return false;
}
};
你当然可以使用find()
:
Point(0,0)
if( map.find(Point(0,0)) == map.end() ){ /*Element not found*/ }
如果您可以使用c++11,那么std::unorderd_map
也是一个选项,因为您不需要为密钥类设置operator<
。
您甚至可以使用std::pair<Point,Point>
作为映射的键。
另一个选择是使用像这样的4D数组:
mat[i][j][k][l] = 5.0f;
你只需要屏幕上像素所在的width
。这样的函数很容易实现,因为width * height
等于像素的数量,您可以编写x + y * width
来表示地图上的任何像素。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- C++ 多重继承:使用基类 A 的实现实现基类 B 的抽象方法
- 如何自己为我自己的shared_ptr实现实现别名构造函数
- 这个UTF-8实现实现是定义的还是定义良好的
- 我的 PRNG 实现与我尝试复制的实现有何不同?