3

The code is from a book which teaching OpenCV. I ran the code but it always showing error.

import cv2 
casc_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(casc_path)
faceCascade = cv2.CascadeClassifier(casc_path)
faces = faceCascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30,30), flags = cv2.CASCADE_SCALE_IMAGE)
imgheight=image.shape[0]
imgwidth=image.shape[1] 
cv2.rectangle(image, (10,imgheight-20), (110,imgheight), (0,0,0), -1)
cv2.putText(image,"Find " + str(len(faces)) + " face!", (10,imgheight-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
for (x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w, y+h),(128,255,0),2)

cv2.namedWindow("facedetect")
cv2.imshow("facedetect", image)
cv2.waitKey(0)  
cv2.destroyWindow("facedetect")

And the error is here.

File "K:/pyCharm_object/OpevCV.py", line 2, in <module>
casc_path = cv2.data.harrcascades + "harrcascade_frontalface_default.xml"
AttributeError: module 'cv2' has no attribute 'data'
蔡承諺
  • 31
  • 1
  • 4
  • 1
    Does this answer your question? [AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'](https://stackoverflow.com/questions/44633378/attributeerror-module-cv2-cv2-has-no-attribute-createlbphfacerecognizer) – Ruli Dec 18 '20 at 13:39
  • 1
    or possibly with `pip install opencv-contrib-python --upgrade` – Ruli Dec 18 '20 at 13:39
  • what version of OpenCV do you use? I have v4.1.1 handy and it does have `cv2.data.haarcascades` – Christoph Rackwitz Dec 18 '20 at 18:39
  • the issue is not about needing contrib. not all import errors are due to the same reason. – Christoph Rackwitz Dec 18 '20 at 18:40

4 Answers4

4

OpenCV comes with and knows where to look for the pre-trained classifiers.

You could omit that line and simply do:

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
3
pip install opencv-contrib-python --upgrade 

As suggested by @Ruli in the comments has resolved this problem for me.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
SamYoda
  • 31
  • 2
-1

Are you confident about the openCV package you have installed? If you have the

opencv-contrib-python package you shouldn't be looking at that error.

-1

Just find your location of haarcascade_frontalface_default.xml by searching in file explorer. Then copy the path of the required xml file and paste path in raw form:

casc_path = (r"**your path**\haarcascade_frontalface_default.xml")

Example:

casc_path = (r"C:\Users\User_name\miniconda3\pkgs\libopencv-4.5.3-py39h4b6fd43_5\Library\etc\haarcascades\haarcascade_frontalface_default.xml")

This worked for me. :)

ouflak
  • 2,458
  • 10
  • 44
  • 49