1

I am currently implementing a general classification program where the user inputs a labeled dataset and a machine learning technique from opencv and the program trains this Classifier. Since for some classifiers (in my example Neural Nets) the input data structure needs to be different (not an integer as class label, but an array composed of index -1/1 for each class), I apply a converter of the integer class label to an array class label. Since I only need to do this for the Classifier ANN_MLP and not the other possible classifiers, I am looking for a way to check which kind of StatModel (superclass of all classifiers in opencv) my input classifier is.

So I am looking for something like this:

void validate(cv::ml::StatModel* classifier){
    if(classifier.ofType(cv::ml::ANN_MLP))
        do something
    else
        do something else
}

Does anyone know if there is a functionality in opencv to check for the type of sub-/superclasses?

I tried to check

if(typeid(cv::ml::ANN_MLP).hash_code() == typeid(classifier).hash_code())

and

if(typeid(cv::ml::ANN_MLP)==typeid(classifier))

from C++ equivalent of instanceof, but this always returns false, probably because the classifier is cast to a StatModel if used in this function? But should the underlying structure of the subclass not be saved somewhere? Sorry if this is a stupid question, but I am new to this kind of "casting"/instance-problems... Any help is much apprechiated!! Thanks:)

Andrea

Seastar
  • 386
  • 2
  • 19
  • The canonical C++ way to do that is a `dynamic_cast` and a check for null result. – Bartek Banachewicz Jul 27 '17 at 09:52
  • Ah, perfect, that was easy;) ... since in the post I mentioned, `dynamic_cast` was said to be ineffective and the type_id condition I tried was suggested. Do you know why this returns false in my case? – Seastar Jul 27 '17 at 10:01
  • [Didn't you mix up value type and pointer type there?](http://coliru.stacked-crooked.com/a/be2aef2e22dd079b). You have `StatModel*` and `cv::ml:ANN_MLP` to compare – Bartek Banachewicz Jul 27 '17 at 10:09
  • You are right, now both methods work! Thanks a lot!! – Seastar Jul 27 '17 at 10:14

1 Answers1

0

You forgot that the parameter passed is of pointer type: StatModel*. As such, you need to either compare it to a pointer type of cv::ml::ANN_MLP or strip it from the type passed in.

Alternatively, dynamic_cast, albeit slower, will also work for subtypes of ANN_MLP.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135