Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Error with cv2.CascadeClassifier() using Trained Classifier

The below code runs fine when 'cascade.xml' is replaced with the 'haarcascade_frontalface_default.xml' classifier included with opencv. However, it throws this error using the cascade.xml file I created by going through the training process.

Traceback (most recent call last): File "/home/pi/Desktop/test_cascade.py", line 4, in <module> face_cascade = cv2.CascadeClassifier('cascade.xml') error: /home/pi/opencv-3.2.0/modules/core/src/persistence.cpp:2659: error: (-212) cascade.xml(114): Preliminary end of the stream in function icvXMLParseTag

Both xml files are in the same directory in the python script, so it seems there is something wrong with my xml file. I noticed the format of the two is different, and it seems some things are missing from the end of mine. Did training not complete correctly? It went through five stages as requested with the stages parameter. Here's the xml file since I can't attach it https://pastebin.com/h0h043nR

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('cascade.xml')
img = cv2.imread('image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = img[y:y+h, x:x+w]
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()