Bartłomiej 'furas' Burek
furas.pl
# prywatne notatki - Python, Linux, Machine Learning, etc.

Problem to load file haarcascades in OpenCV [GB]

Sometimes tutorial loads haarcascades file installed with OpenCV like this

eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

but when we run code

import numpy as np
import cv2

eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

image = np.array([1,2,3], dtype='uint8')
eye_cascade.detectMultiScale(img, 1.3, 5)

then we get error

cv2.error: OpenCV(4.1.2) /io/opencv/modules/objdetect/src/cascadedetect.cpp:1689: error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

Problem is that it needs full path to this file - so we have to add folder to this path.

Lucky OpenCV has special variable with full path to this folder

import cv2

print(cv2.data.haarcascades)

and we can use it to create full path to this file

eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')

You can even use it see all .xml files in this folder

import os
import cv2

for name in sorted(os.listdir(cv2.data.haarcascades)):
    if name.endswith('.xml'):
        print(name)

Result

haarcascade_eye.xml
haarcascade_eye_tree_eyeglasses.xml
haarcascade_frontalcatface.xml
haarcascade_frontalcatface_extended.xml
haarcascade_frontalface_alt.xml
haarcascade_frontalface_alt2.xml
haarcascade_frontalface_alt_tree.xml
haarcascade_frontalface_default.xml
haarcascade_fullbody.xml
haarcascade_lefteye_2splits.xml
haarcascade_licence_plate_rus_16stages.xml
haarcascade_lowerbody.xml
haarcascade_profileface.xml
haarcascade_righteye_2splits.xml
haarcascade_russian_plate_number.xml
haarcascade_smile.xml
haarcascade_upperbody.xml
Książki: python-dla-kazdego-podstawy-programowania python-wprowadzenie python-leksykon-kieszonkowy python-receptury python-programuj-szybko-i-wydajnie python-projekty-do-wykorzystania black-hat-python-jezyk-python-dla-hackerow-i-pentesterow efektywny-python-59-sposobow-na-lepszy-kod tdd-w-praktyce-niezawodny-kod-w-jezyku-python aplikacje-internetowe-z-django-najlepsze-receptury