Search code examples
pythonopencvtypechecking

check type of classifier object in python cv2?


How do I check that I've got a cv2.CascadeClassifier object in openCV 2?
Atm, if I run it with a wrong path it won't let me know and will give me dud results. So I want this check but don't know the correct call/syntax.

input: cascadePath = "correctPath.xml"

# load the trained cascade
print("loading classifier...")
trainedCascade = cv2.CascadeClassifier(cascadePath)

Try1:

if type(trainedCascade) is not 'cv2.CascadeClassifier':
        print(type(trainedCascade))
        raise Exception("no classifier found at this path")

Result1:

<type 'cv2.CascadeClassifier'>
Exception: no classifier found at this path

Try2:

if not isinstance(trainedCascade, type(cv2.CascadeClassifier)):
    raise Exception("no classifier found at this path")

Result2: Exception: no classifier found at this path

Try3 empty() method:

  if cv2.CascadeClassifier.empty():
        print("trained cascade is empty!")

Result3:

AttributeError: 'builtin_function_or_method' object has no attribute 'empty'


Solution

  • You're almost there:

    if not isinstance(trainedCascade, cv2.CascadeClassifier):
    

    update: if your getting TypeError: isinstance() arg 2 must be a class.., that means that cv2.CascadeClassifier is not a class, but probably some sort of factory function. Depending on how opaque it's been made, you might not be able to check the returned type. You could try:

    if trainedCascade.empty():