簡體   English   中英

OpenCV中cv :: Mat的自定義類型

[英]Custom defined type for cv::Mat in OpenCV

我想用自定義類型的cv :: Mat創建一個數組。 這是我的代碼:

typedef struct{
  int x;
  int y;
  float prob;
}CellXY;

void main(){

  cv::Mat_<CellXY> map(10, 10);

  std::cout << "Width = " << map.cols << ", Height = " << map.rows << std::endl;
  std::cout << "### Assignment ###" << std::endl;
  for (int j=0; j<map.rows; j++){
    for (int i=0; i<map.cols; i++){
      map.at<CellXY>(j, i).x = i;
      map.at<CellXY>(j, i).y = j;
      map.at<CellXY>(j, i).prob = (float)(i + j * map.cols);

      std::cout << map.at<CellXY>(j, i).prob 
        << " (" << map.at<CellXY>(j, i).x
        << "," << map.at<CellXY>(j, i).y
        << ")\t";
    }
    std::cout << std::endl;
  }

  std::cout << "### Display ###" << std::endl;
  for (int j=0; j<map.rows; j++){
    for (int i=0; i<map.cols; i++){
      std::cout << map.at<CellXY>(j, i).prob 
        << " (" << map.at<CellXY>(j, i).x
        << "," << map.at<CellXY>(j, i).y
        << ")\t";
    }
    std::cout << std::endl; 
  }
  map.release();
}

但是“分配”和“顯示”部分之間的結果不一樣:

如何使這些結果相同?

這是因為OpenCV不知道你班級的DataType 你需要專門化它,如:

typedef struct {
    int x;
    int y;
    float prob;
}CellXY;


// Add this!!!!!!
namespace cv {
template<> class DataType<CellXY>
{
public:
    typedef CellXY      value_type;
    typedef value_type  work_type;
    typedef value_type  channel_type;
    typedef value_type  vec_type;
    enum { generic_type = 0,
        depth        = CV_32F, // Might cause problems... I'm saying it's all made of floats (and not 2 int a 1 float)
        channels     = 3,
        fmt          = (int)'p',
        type         = CV_MAKETYPE(depth, channels)
    };
};
}

void main() {
    ...
}

但是,總的來說,我認為最好避免弄亂這些實現細節,只使用更好的數據結構。 建議是: 僅將Mat用於原始類型 事實上,你不能在其他OpenCV函數中使用它...

這里有幾種方法可以解決您的問題:

  1. 使用另一種數據結構:例如std::vector<std::vector<CellXY>> std::vector<std::vector<CellXY>> std::vector<CellXY>
  2. 創建一個CellXYMatrix類來處理存儲CellXY

     class CellXYMatrix { std::vector<CellXY> _mat; // your matrix of CellXY int _r; // rows int _c; // cols public: CellXYMatrix(int rows, int cols) : _r(rows), _c(cols), _mat(rows * cols) {}; void set(int row, int col, const CellXY& cell) { _mat[row * _c + col] = cell; } CellXY& get(int row, int col) { return _mat[row * _c + col]; } } 

    您最終可以重載operator()以使訪問類似於OpenCV Mats。

  3. 如果CellXYxy字段指向矩陣位置,為什么需要它們? 您可以簡單地為您的概率設置Mat1f (也就是Mat_<float> ),x,y是矩陣中的位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM