如何在openCV 2中检查我是否有cv2.CascadeClassifier
个对象?
Atm,如果我用错误的路径运行它,它不会让我知道,并会给我哑弹效果。所以我想要这个检查,但不知道正确的调用/语法。
输入
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")
结果1:
<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")
结果2:
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'
答案 0 :(得分:0)
你快到了:
if not isinstance(trainedCascade, cv2.CascadeClassifier):
更新:如果您获得TypeError: isinstance() arg 2 must be a class..
,则表示cv2.CascadeClassifier
不是类,但可能是某种工厂功能。根据它的不透明程度,您可能无法检查返回的类型。你可以尝试:
if trainedCascade.empty():
答案 1 :(得分:0)
我遇到了同样的问题。正如@thebjorn所说,你可以使用
if isinstance(object, class):
如果您收到错误TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
,可以尝试:
if isinstance(trainedCascade, type(cv2.CascadeClassifier())):
通过这种方式,您可以构建所需类型的对象,然后根据目标对象进行检查。