将值映射到像素对-如何实现数据结构

Mapping value to pixel pairs - How to implement the data structure

本文关键字:何实现 实现 数据结构 映射 像素      更新时间:2023-10-16

我有一个函数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():

来检查map中是否有元素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来表示地图上的任何像素。