0

so I am trying to get the value of a matrix, which type I do not know, using row and column value. I basically want to implement the following:

bool someFunction(cv::Mat m){
   return m(1,0) != 0;
}

I know this will error out since I need to specify the type like so m.at< Type >(1,0) but I would not know the type.

I tried doing the following: m.at< m.type() >(1,0) but that, of course, errors out.

I am wondering what could potentially work here. Thanks!

Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96
  • 2
    If you don't know the type of the element, how do you know that comparing the element to a number (0) is a legal / reasonable operation? – Niko Oct 13 '14 at 22:04

2 Answers2

1

A not so elegant solution. Use depth and a switch case.

#include<cv.h>
#include<stdint.h>

using namespace cv;
using namespace std;

bool someFunction(Mat m) {
    switch (m.depth()){
        case CV_8U:
            return m.at<uint8_t>(1,0) != 0;
        case CV_8S:
            return m.at<int>(1,0) != 0;
        case CV_16U:
            return m.at<uint16_t>(1,0) != 0;
        case CV_16S:
            return m.at<int16_t>(1,0) != 0;
        case CV_32S:
            return m.at<int32_t>(1,0) != 0;
        case CV_32F:
            return m.at<float>(1,0) != 0;
        case CV_64F:
            return m.at<double>(1,0) != 0;
    }
}

int main() {
    Mat m(2,2, CV_8UC1);
    cout << someFunction(m) << endl;
}
Vasanth
  • 1,238
  • 10
  • 14
0

I am assuming that you are doing this for single channel images, but you will get an idea even for > 1 channel images.

You can change your function to

template<class T>
bool someFunction(cv::Mat_<T> m) {
   return m(1,0) != 0;
};

And you can call the function like -

someFunction<uchar>(gray);

Here, I am assuming that you know the type, from the function you are calling. In place of uchar, you can use any data type your Mat object is of. If you want to automate this task also, check here.

Community
  • 1
  • 1
bikz05
  • 1,575
  • 12
  • 17