How do I print a Mat element using this basic C wrapper for the C++ Mat Class ptr object

不问归期 提交于 2019-12-11 17:27:07

问题


I'm writing a C wrapper for some OpenCV C++ code and I have 2 functions I use to create a Mat object and set data to it cv_create_Mat_type and cv_Mat_ptr_index respectively. The functions are as they need to be, I can't change them because there part of a project I'm working on with someone.

My question is how do I print the matrix that cv_Mat_ptr_index is filling up, as it fills it up inside the for loop. The return on cv_Mat_ptr_index is a uchar* I tried dereferencing it but I need to know how to get at the data inside the return of cv_Mat_ptr_index, the uchar*, because I'm sure, and correct me if I'm wrong, that it contains the element currently allocated into the matrix mat from the data array in the below code .

Thanks in advance for any takers.

    #include "opencv2/highgui/highgui.hpp"
    #include "opencv2/highgui/highgui_c.h"
    #include <iostream>

    using namespace cv;
    using namespace std;



    uchar* cv_Mat_ptr_index(Mat* self, int i) {
        return self->ptr(i);
    }

    Mat* cv_create_Mat_typed(int rows, int cols, int type) {
        return new Mat(rows, cols, type);
    }

    int main(  )
    {

    float data[4][2] = { {501, 10}, {255, 10}, {501, 255}, {10, 501} };
    Mat* mat = cv_create_Mat_typed(4, 2, CV_64F);
    for(int i = 0; i < 4; i++)
        for(int j = 0; j < 2; j++)
             cv_Mat_ptr_index(mat, i)[j] = data[i][j];


    }

Edit:

I'm trying to basically print a matrix using cv_Mat_ptr_index, hopefully while its setting the data to the matrix "mat" but If I cant do that I was hoping you can show me how to use cv_Mat_ptr_index to print the contents of the matrix "mat"

i/e like cout << mat; would normally do but I can't use cout << mat; because it is a pointer.

I was also hoping you can show me how to print an element of "mat" with it because it already has access to the ptr object...I can't change cv_Mat_ptr_index in any way though...


回答1:


Mat::ptr(i) gives a pointer to the ith element in the matrix, seen as a long 1 dimensional vector.

Mat::at<double>(i,0) gives a reference to the 0th element of the ith row of the matrix, seen as a 2D matrix as normal, so you can take its address.

double* cv_Mat_ptr_index(Mat* self, int i) {
        return &self->at<double>(i,0);
}

Don't forget to dereference the pointer you get back from cv_Mat_ptr_index(...) when you assign to it, eg

   *cv_Mat_ptr_index(mat, i)[j] = data[i][j];
// ^-- note dereference


来源:https://stackoverflow.com/questions/22469666/how-do-i-print-a-mat-element-using-this-basic-c-wrapper-for-the-c-mat-class-pt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!